javascript – 如何将数据从嵌套数组(在对象数组中)推送到新数组?同时保持其嵌套结构

我有一个包含多个对象的数组.这些对象还包含这样的对象数组:

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"}
            ]
        }
    ];

我想将两个兴趣数组推送到一个新的数组,如下所示:

newArray = 
    [
        [{id: 9, name: "basketball"}, {id: 8, name: "art"}],
        [{id: 7, name: "reading"},{id: 6, name: "running"}]
    ];

这会将数据推送到新数组,但数据不会以这种方式嵌套:

data.map(v => { v.interests.map(x => { newArray.push({name: x.name, id:x.id}) }) })

如何在保持嵌套结构的同时将兴趣数据推送到新阵列?

最佳答案
只需.映射每个项目的兴趣:

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);

映射时,您不希望使用push到您之前创建的新数组;相反,您希望为每个新数组项使用return(或使用箭头函数的隐式返回). (您目前正在使用.map作为forEach)

如果您不想仅映射兴趣数组并且还需要转换对象,那么它会更复杂一些;你还必须使用嵌套地图:

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 – 如何将数据从嵌套数组(在对象数组中)推送到新数组?同时保持其嵌套结构 - 代码日志