我正在尝试压平一个看起来像这样的对象,
{
O75376: {
ABC: [],
XYZ: ["a", "b", "c"],
FGH: ["x", "y", "z"]
},
O75378: {
ABC: [],
XYZ: ["a", "b", "c"],
FGH: ["x", "y", "z"]
},
}
我希望它像 075376: ["a","b","c","x","y","z"], 075378: ["a","b",“c”,“x”,“y”,“z”],
const flat = reduce(data, (accumulator, content, key) => {
accumulator[key] = flatMap(content, (x, y) => {
return map(x, b => {
return y + '~' + b
})
})
return accumulator;
}, {});
这适用于 lodash,但我无法弄清楚这如何在 ES6 中实现。
最佳答案
您可以减少对象的条目,并通过展平所有数组将每个键添加到新对象。
const obj = {
"O75376": {
ABC: [],
XYZ: ["a", "b", "c"],
FGH: ["x", "y", "z"]
},
"O75378": {
ABC: [],
XYZ: ["a", "b", "c"],
FGH: ["x", "y", "z"]
},
};
const res = Object.entries(obj).reduce((acc,[key,val])=>(
acc[key] = Object.values(val).flat(), acc
), {});
console.log(res);
如果只能使用 ES6,则可以使用 Array.prototype.concat.apply([], array)
代替 array.flat()
。
const obj = {
"O75376": {
ABC: [],
XYZ: ["a", "b", "c"],
FGH: ["x", "y", "z"]
},
"O75378": {
ABC: [],
XYZ: ["a", "b", "c"],
FGH: ["x", "y", "z"]
},
};
const res = Object.entries(obj).reduce((acc,[key,val])=>(
acc[key] = Array.prototype.concat.apply([], Object.values(val)), acc
), {});
console.log(res);
关于javascript - 缩小并扁平化一个物体的物体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62701749/