为了账号安全,请及时绑定邮箱和手机立即绑定

将多个对象合并为一个对象并组合属性 JavaScript

将多个对象合并为一个对象并组合属性 JavaScript

暮色呼如 2022-07-21 22:16:29
我在一个数组中有多个对象,我想合并所有具有相同 id 的对象,但我也想合并一个属性中的所有值(在这种情况下,通道)这是代码:defaultArray = [  {    id: "FirstId",    name: "Some random name"    channels: [{      id: "Channel-ASD",      name: "Channel ASD"    }]  },  {    id: "FirstId",    name: "Some random name"    channels: [{      id: "Channel-QWE",      name: "Channel QWE"    }]  },  {    id: "SecondId",    name: "Some random name"    channels: [{      id: "Channel-QAZ",      name: "Channel QAZ"    }]  }];预期输出:newArray = [  {    id: "FirstId",    name: "Some random name"    channels: [      {        id: "Channel-ASD",        name: "Channel ASD"      },      {        id: "Channel-QWE",        name: "Channel QWE"      }    ]  },  {    id: "SecondId",    name: "Some random name"    channels: [{      id: "Channel-QAZ",      name: "Channel QAZ"    }]  }]
查看完整描述

1 回答

?
慕莱坞森

TA贡献1810条经验 获得超4个赞

你需要学习filter, map, reduce, some, ...


let defaultArray = [

  {

    id: "FirstId",

    name: "Some random name",

    channels: [{

      id: "Channel-ASD",

      name: "Channel ASD"

    }]

  },

  {

    id: "FirstId",

    name: "Some random name",

    channels: [{

      id: "Channel-QWE",

      name: "Channel QWE"

    }]

  },

  {

    id: "SecondId",

    name: "Some random name",

    channels: [{

      id: "Channel-QAZ",

      name: "Channel QAZ"

    }]

  }

];


let transformed= defaultArray.reduce((result, item, index, original)=>{

  if (result.some(i=>i.id===item.id)) return result;

  let channels = original.reduce((r,i)=>{

    i.id===item.id && (r=[...r, ...i.channels]);

    return r;

  },[]);


  result.push({

    ...item,

    channels

  });

  return result;

},[]);


console.log(JSON.stringify(transformed,null,2));


查看完整回答
反对 回复 2022-07-21
  • 1 回答
  • 0 关注
  • 150 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信