首页 > 解决方案 > 将一个特定的对象道具从一个数组移动到另一个对象数组,如果条件(JavaScript ES6)

问题描述

我有 2 个对象数组从 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,它将把整个对象从 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"
  },

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

期望的输出:

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

标签: javascriptarraysobject

解决方案


您可以使用它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' },
  .
  .
  .
}

推荐阅读