3 回答
TA贡献1963条经验 获得超6个赞
您可以使用 flatMap
let data = [{"foo": {"name":"foo-name"},"bar": {"name":"bar-name"}},{"baz": {"name":"baz-name"}}]
let final = data.flatMap(a => Object.entries(a).map(([k, v]) => ({
[k]: v
})))
console.log(final)
TA贡献2051条经验 获得超10个赞
一种选择是reduce进入一个数组,迭代每个对象的条目并将它们推送到累加器:
const data = [
{
"foo": {"name":"foo-name"},
"bar": {"name":"bar-name"}
},
{
"baz": {"name":"baz-name"}
}
];
const output = data.reduce((a, obj) => {
Object.entries(obj).forEach(([key, val]) => {
a.push({ [key]: val });
});
return a;
}, []);
console.log(output);
TA贡献2021条经验 获得超8个赞
我会使用一个简单for-of的Object.entries映射到对象:
const result = [];
for (const obj of data) {
result.push(
...Object.entries(obj).map(
([key, value]) => ({[key]: value})
)
);
}
现场示例:
const data = [
{
"foo": {"name":"foo-name"},
"bar": {"name":"bar-name"}
},
{
"baz": {"name":"baz-name"}
}
];
const result = [];
for (const obj of data) {
result.push(
...Object.entries(obj).map(
([key, value]) => ({[key]: value})
)
);
}
console.log(result);
添加回答
举报