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?
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?
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; }