js 这种[{a:1},{a:{b:1})]二层对象如何处理成一层
时间: 2024-03-10 20:46:32 浏览: 13
您可以使用递归函数来处理这个问题。以下是一个处理二层对象的JavaScript函数示例:
```
function flattenObject(obj) {
var flattenedObj = {};
function recurse(currentObj, currentPath) {
for (var key in currentObj) {
var value = currentObj[key];
var newPath = currentPath + (currentPath ? '.' : '') + key;
if (typeof value === 'object' && value !== null) {
recurse(value, newPath);
} else {
flattenedObj[newPath] = value;
}
}
}
recurse(obj, '');
return flattenedObj;
}
// 示例
var obj = [{a:1}, {a:{b:1}}];
var flattened = flattenObject(obj);
console.log(flattened); // 输出:{ "0.a": 1, "1.a.b": 1 }
```
在这个函数中,我们首先定义了一个空对象 `flattenedObj`,用于存储扁平化后的结果。然后我们定义了一个递归函数 `recurse`,用于遍历对象并将其扁平化。在每次递归中,我们检查当前键值对的值是否为对象,如果是,我们就递归地调用 `recurse` 函数;如果不是,我们就将键值对添加到 `flattenedObj` 中,并使用路径字符串作为键。最后,我们调用 `recurse` 函数并返回 `flattenedObj`。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)