-2

Here's the arrays:

const firstArr = [
  {
    id: 1,
    code: '1'
  },
  {
    id: 2,
    code: '2'
  },
  {
    id: 3,
    code: '3'
  },
]

const secondArr = [
  {
    id: 1,
    code: '1',
    bool: true,
  },
  {
    id: 2,
    code: '2',
    bool: true,
  },
]

Desired result is:

const overwrittenArr = [
  {
    id: 1,
    code: '1',
    bool: true,
  },
  {
    id: 2,
    code: '2',
    bool: true,
  },
  {
    id: 3,
    code: '3'
  },
]

secondArr should overwrite the firstArr by the code value, if it's exact the same value as in the firstArr, then it should be replaced with the object from the secondArr. I've tried to do that with filter, but had no success.

Alexander Kim
  • 17,304
  • 23
  • 100
  • 157
  • 2
    Please show us what you've done so far. – Wais Kamal Jun 30 '21 at 18:10
  • Please visit [help], take [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) – mplungjan Jun 30 '21 at 18:13

3 Answers3

1

You could use forEach in order to mutate the first array like this:

const firstArr = [
  {
    id: 1,
    code: '1'
  },
  {
    id: 2,
    code: '2'
  },
  {
    id: 3,
    code: '3'
  },
]

const secondArr = [
  {
    id: 1,
    code: '1',
    bool: true,
  },
  {
    id: 2,
    code: '2',
    bool: true,
  },
]

secondArr.forEach(x => Object.assign(firstArr.find(y => y.id === x.id) || {}, x))

console.log(firstArr)
Guerric P
  • 30,447
  • 6
  • 48
  • 86
0

You could assign the second array to the first.

const
    firstArr = [{ id: 1, code: '1' }, { id: 2, code: '2' }, { id: 3, code: '3' }],
    secondArr = [{ id: 1, code: '1', bool: true }, { id: 2, code: '2', bool: true }];

Object.assign(firstArr, secondArr);

console.log(firstArr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Object.assign to the rescue!

const firstArr = [
  {
    id: 1,
    code: '1'
  },
  {
    id: 2,
    code: '2'
  },
  {
    id: 3,
    code: '3'
  },
];

const secondArr = [
  {
    id: 1,
    code: '1',
    bool: true,
  },
  {
    id: 2,
    code: '2',
    bool: true,
  },
];

const overwrittenArr = [
  {
    id: 1,
    code: '1',
    bool: true,
  },
  {
    id: 2,
    code: '2',
    bool: true,
  },
  {
    id: 3,
    code: '3'
  },
];

let result = Object.assign(firstArr, secondArr);

alert(JSON.stringify(result) === JSON.stringify(overwrittenArr));
AGE
  • 3,752
  • 3
  • 38
  • 60