繁体   English   中英

如果条件(JavaScript ES6),将一个特定的 object 道具从一个数组移动到另一个对象数组

[英]move one specific object prop from one array to another array of objects, if condition (JavaScript ES6)

我有 2 个 arrays 从 2 个不同的 fetch 返回的对象

const result1 = [
  {
    name: 'matteo',
    age: 20,
    id: 1,
  },
  {
    name: 'luca',
    age: 24,
    id: 2,
  },
];

const result2 = [
  {
    warnings: 'yes',
    hobby: "tennis",
    id: 1,
  },
  {
    warnings: 'many',
    hobby: "ping pong",
    id: 2,
  },
];

这是我目前的方法,但如果它们具有相同的 id,它将把整个 object 从 result2 合并到 result1

const t = result2.reduce((acc, curr) => {
    acc[curr.id] = curr;
    return acc;
  }, {});

  const d = result1.map((d) =>
    Object.assign(d, t[d.id]) 
  );

目前的结果是:

{
    name: 'matteo',
    age: 20,
    id: 1,
warnings: "yes",
hobby: "tennis"
  },
  {
    name: 'luca',
    age: 24,
    id: 2,
warnings: "many",
hobby: "ping pong"
  },

我只想将警告道具从第二个对象数组移动到第一个对象数组中,其中 object 的 id 相等

所需的 output:

const result3 = [
      {
        name: 'matteo',
        age: 20,
        id: 1,
        warnings: "yes"
      },
      {
        name: 'luca',
        age: 24,
        id: 2,
        warnings: "many"
      },
    ];

您可以使用map创建一个新数组,并find任何具有匹配 id 的警告:

 let result1 = [ { id: 1, name: 'a', age: 1 }, { id: 2, name: 'b', age: 2 }, { id: 3, name: 'c', age: 3 }, { id: 4, name: 'd', age: 4 } ]; let result2 = [ { id: 1, hobby: 'aa', warnings: 'aaa' }, { id: 2, hobby: 'bb', warnings: 'bbb' }, { id: 4, hobby: 'dd', warnings: 'ddd' } ]; let includeWarnings = (data, warningsArr) => data.map(obj => { // `w` will be undefined if no matching warning is found let w = warningsArr.find(warn => warn.id === obj.id); // Return all the data in `obj`, and the "warnings" property // of `w` if `w` is defined return {...obj, ...(w? { warnings: w.warnings }: {}) }; }); console.log(includeWarnings(result1, result2));

请注意,如果您的数据格式的结构考虑到了id映射,您可能会做得更好:

let result1 = {
  id1: { name: 'name1', age: 1 },
  id2: { name: 'name2', age: 2 },
  .
  .
  .
}

let result2 = {
  id1: { hobby: 'hobby1', warnings: 'warnings1' },
  id2: { hobby: 'hobby2', warnings: 'warnings2' },
  .
  .
  .
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM