gpt4 book ai didi

javascript - 将对象数组数组简化为对象数组

转载 作者:行者123 更新时间:2023-12-01 10:17:04 25 4
gpt4 key购买 nike

var data=[
{name:'Sam',ssn:123, age:25, hobbies:[{name:'cricket'},{name:'football'}]},
{name:'John',ssn:234, age:25, hobbies:[{name:'cricket'},{name:'football'}]},
{name:'Mathew',ssn:345, age:25, hobbies:[{name:'cricket'},{name:'football'}]}
];

想要将其生成为以下格式

[      
{name:'Sam',ssn:123, age:25,hobbies:[{name:'cricket'}]},
{name:'Sam',ssn:123, age:25,hobbies:[{name:'football'}]},
{name:'John',ssn:234, age:25,hobbies:[{name:'cricket'}]},
{name:'John',ssn:234, age:25,hobbies:[{name:'football'}]},
{name:'Mathew',ssn:345, age:25,hobbies:[{name:'cricket'}]},
{name:'Mathew',ssn:345, age:25,hobbies:[{name:'football'}]}
];

我尝试过以下方法。没有任何想法。我已经添加了一些reduce方法的基本功能,但接下来没有任何想法来压平它。

var flatten = data.reduce((curr, next) => {
var temp = [];
return (curr.hobbies = { name: "cricket" });
temp.push(curr);
return curr;
});

最佳答案

flatMap() 是这里的最佳选择。

var data=[
{name:'Sam',ssn:123, age:25, hobbies:[{name:'cricket'},{name:'football'}]},
{name:'John',ssn:234, age:25, hobbies:[{name:'cricket'},{name:'football'}]},
{name:'Mathew',ssn:345, age:25, hobbies:[{name:'cricket'},{name:'football'}]}
];

const res = data.flatMap(x => x.hobbies.map(h => ({...x, hobbies: [h]})));
console.log(res)

关于javascript - 将对象数组数组简化为对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60606797/

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