【问题标题】:Adding a property in an array of objects in a separate array of objecs by id [closed]通过 id 在单独的对象数组中的对象数组中添加属性 [关闭]
【发布时间】:2022-01-05 04:54:02
【问题描述】:

我有这两个数组,我想通过比较 parent idchild parentsId 将第二个数组作为额外属性推送到它的父级,我已经花了几个小时来获得我想要的输出,帮助将是非常感谢

第一个数组

const parent = [
      {
        id: 1,
        name: 'john',
        age: 32,
      },
      {
        id: 2,
        name: 'jane',
        age: 44,
      },
    ];

第二个数组

const child = [
      {
        parentId: 1,
        name: 'mike',
        age: 5,
      },
      {
        parentId: 2,
        name: 'michelle',
        age: 6,
      },
      {
        parentId: 2,
        name: 'morgan',
        age: 7,
      },
    ];

这是我想要的结果,所以基本上孩子将通过使用 parentId 填充到其父母

  const parent = [
      {
        id: 1,
        name: 'john',
        age: 32,
        children: [
          {
            parentId: 1,
            name: 'mike',
            age: 5,
          },
        ],
      },
      {
        id: 2,
        name: 'jane',
        age: 44,
        children: [
          {
            parentId: 2,
            name: 'michelle',
            age: 6,
          },
          {
            parentId: 2,
            name: 'morgan',
            age: 7,
          },
        ],
      },

【问题讨论】:

  • 你可以试试child.reduce((p,c) => doSomethingWithPandC(p,c), parent)
  • @Redu 我的 javascript 不是很好,对不起

标签: javascript arrays object


【解决方案1】:

您可以结合使用.map().filter() 和展开语法:

const parent = [{ id: 1, name: "john", age: 32 }, { id: 2, name: "jane", age: 44}];
const child = [{ parentId: 1, name: "mike", age: 5}, { parentId: 2, name: "michelle", age:6}, { parentId: 2, name: "morgan", age: 7}];

const result = parent.map(person => ({
  ...person,
  children: child.filter(({ parentId }) => parentId === person.id)
}));

console.log(result);

编辑:我不确定您的问题到底为什么被关闭。我不会说它缺乏“焦点”。可能是因为您没有提供有关如何尝试解决问题的信息,或者您遇到了哪些错误。下次请提供更多信息。

【讨论】:

  • 太棒了!赞赏!
猜你喜欢
  • 2018-02-08
  • 1970-01-01
  • 1970-01-01
  • 2019-05-29
  • 1970-01-01
  • 2018-07-30
  • 2013-05-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多