简体   繁体   中英

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

I have 2 arrays of objects returning from 2 different 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,
  },
];

This is my current approach but it will merge the entire object from result2 to result1 if they have the same id

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

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

The current result is:

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

I would like to move only the warnings prop from the second array of objects into the first array of objects where the id of object is equal

Desired output:

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

You can use map to create a new array, and find to get any warning with a matching 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));

Note you'd potentially be better off if your data format was structured with id mappings in mind:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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