0

I have 2 array

var arr = [{ 1: a }, { 2: b }, { 3: d }];

var arr1 = [{ 1: a }, { 2: c }, { 3: e }];

I want to copy arr1 key's value to arr. below I want output result

arr = [{ 1: a }, { 2: c }, { 3: e }];

How it is possible to achieve?

  • 4
    You might need a better example or more information. Your example could be obtained with `arr = [...arr1]`. Or do you need to have new instances of the objects? `arr = arr1.map(a => ({...a})` Or do you need to only update the values that exist in arr, for instance if arr has 2 and 4, do you keep 4 the same or remove it? Do you add the missing values from arr1? – Jason Goemaat May 27 '21 at 15:10
  • Does this answer your question? [Merge two array of objects based on a key](https://stackoverflow.com/questions/46849286/merge-two-array-of-objects-based-on-a-key) – pilchard May 27 '21 at 15:14

1 Answers1

2

You could assign the objects with the wanted object. The result keeps the object references as well as the array reference.

const
    array = [{ 1: 'a' }, { 2: 'b' }, { 3: 'd' }],
    update = [{ 1: 'a' }, { 2: 'c' }, { 3: 'e' }];

array.forEach((o, i) => Object.assign(o, update[i]));

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

If you like only to update a certain property, you need to iterate the array and all entries.

const
    array = [{ 1: 'a' }, { 2: 'b' }, { 3: 'd' }],
    update = [{ 1: 'a' }, { 2: 'c' }, { 3: 'e' }];

array.forEach((o, i) => {
    Object.entries(update[i]).forEach(([k, v]) => {
        if (o[k] !== v) (console.log(o[k], v), o[k] = v);
    })
});

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