admin管理员组文章数量:1356343
I have an array that contains multiple objects. These objects also contain arrays of objects like this:
const data =
[
{
id: 1, name: "Jack", interests:
[
{id: 9, name: "basketball"},
{id: 8, name: "art"}
]
},
{
id: 2, name: "Jenny", interests:
[
{id: 7, name: "reading"},
{id: 6, name: "running"}
]
}
];
I would like to push both interests arrays into a new array like so:
newArray =
[
[{id: 9, name: "basketball"}, {id: 8, name: "art"}],
[{id: 7, name: "reading"},{id: 6, name: "running"}]
];
This pushes the data to the new array, but the data isn't nested anymore this way:
data.map(v => { v.interests.map(x => { newArray.push({name: x.name, id:x.id}) }) })
How can I push the interests data to new array while keeping its nested structure?
I have an array that contains multiple objects. These objects also contain arrays of objects like this:
const data =
[
{
id: 1, name: "Jack", interests:
[
{id: 9, name: "basketball"},
{id: 8, name: "art"}
]
},
{
id: 2, name: "Jenny", interests:
[
{id: 7, name: "reading"},
{id: 6, name: "running"}
]
}
];
I would like to push both interests arrays into a new array like so:
newArray =
[
[{id: 9, name: "basketball"}, {id: 8, name: "art"}],
[{id: 7, name: "reading"},{id: 6, name: "running"}]
];
This pushes the data to the new array, but the data isn't nested anymore this way:
data.map(v => { v.interests.map(x => { newArray.push({name: x.name, id:x.id}) }) })
How can I push the interests data to new array while keeping its nested structure?
Share Improve this question asked May 22, 2018 at 4:27 VialitoVialito 5238 silver badges29 bronze badges1 Answer
Reset to default 12Just .map
the interests
of each item:
const data=[{id:1,name:"Jack",interests:[{id:9,name:"basketball"},{id:8,name:"art"}]},{id:2,name:"Jenny",interests:[{id:7,name:"reading"},{id:6,name:"running"}]}]
const mapped = data.map(({ interests }) => interests);
console.log(mapped);
When mapping, you don't want to use push
to a new array you've created beforehand; instead you want to use return
(or use an arrow function's implicit return) for each new array item. (You're currently using the .map
as a forEach
)
If you don't want to just map the interests
array and need to transform the objects as well, then it's a bit more plicated; you'll have to use a nested map
as well:
const data=[{id:1,name:"Jack",interests:[{id:9,name:"basketball",foo:'bar'},{id:8,name:"art",foo:'bar'}]},{id:2,name:"Jenny",interests:[{id:7,name:"reading",foo:'bar'},{id:6,name:"running",foo:'bar'}]}]
const mapped = data.map(({ interests }) =>
// Use only `id` and `foo` properties, discard the `name`s:
interests.map(({ id, foo }) => ({ id, foo }))
);
console.log(mapped);
本文标签:
版权声明:本文标题:javascript - How to push data from a nested array, inside an array of objects, to a new array? while maintaining its nested stru 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744049839a2582220.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论