gpt4 book ai didi

javascript - 在数组上创建多个对象循环

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:10:38 25 4
gpt4 key购买 nike

所以我有一个数组,它在对象的数组中存储每个用户的爱好。

var hobbies = [
{
"id": 1,
"hobbies": []
},

{
"id": 2,
"hobbies": [
"football"
]
},
{
"id": 3,
"hobbies": [
"football",
"basketball"
]
}
]

我想返回的是一个新的对象数组,但每个爱好都分成了自己的对象,如下所示。

var result = [
{
"id": 2,
"hobby": "football"
},
{
"id": 3,
"hobby": "football"
},
{
"id": 3,
"hobby": "basketball"
}
]

目前的情况是

hobbies.filter((f, i) => f.hobbies.length > 0).map((p, i) => {
while (i < p.hobbies.length) {
return { id : p.id, hobby : p.hobbies[i] };
}
});

只返回

[
{
"id": 2,
"hobby": "football"
},
{
"id": 3,
"hobby": "basketball"
}
]

最佳答案

您可以将 array#reducearray#map 一起使用。遍历每个对象,然后遍历 hobbies 的每个 hobby 并创建对象。

var hobbies = [ { "id": 1, "hobbies": [] }, { "id": 2, "hobbies": [ "football" ] }, { "id": 3, "hobbies": [ "football", "basketball" ] } ],
result = hobbies.reduce((r, {id, hobbies}) => r.concat(hobbies.map(hobby => ({id, hobby}))), []);
console.log(result);

关于javascript - 在数组上创建多个对象循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49049124/

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