gpt4 book ai didi

Javascript - 映射对象成员以返回新的扁平化对象

转载 作者:行者123 更新时间:2023-11-30 07:57:11 26 4
gpt4 key购买 nike

是否有更简单的方法来实现下面的代码?使用 lodash 的回答也将被接受。

var obj = {
dataTable: {
column1: ["1"],
column2: ["2"],
column3: ["3"]
},
dataTable2: {
column4: ["4"],
column5: ["5"],
column6: ["6"]
}
}

var result = {};
var keys = Object.keys(obj);

keys.forEach(function(key) {
var fields = Object.keys(obj[key]);
fields.forEach(function(field) {
result[field] = obj[key][field][0];
});
});

console.log(result)
---> {column1: "1", column2: "2", column3: "3", column4: "4", column5: "5", column6: "6"}

最佳答案

你可以用两个 for...in 循环来做到这一点

var obj = {
dataTable: {
column1: ["1"],
column2: ["2"],
column3: ["3"]
},
dataTable2: {
column4: ["4"],
column5: ["5"],
column6: ["6"]
}
}, result = {}

for (p in obj) {
for (a in obj[p]) {
result[a] = obj[p][a].join('');
}
}

console.log(result);

关于Javascript - 映射对象成员以返回新的扁平化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37034640/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com