Since we are dealing with objects, the assignment operator = to “copy” them is unwise: because it will not be copying, but creating reference references to objects in array2 elements in array2 (that is, the first array will not actually contain assigned thus objects).
To copy the fields of an object, it is reasonable to use one of the following methods (the list does not end there, but these two are basic):
- recursive function: pass through the fields of the source object "in depth" to the level of primitives, and assign them to the corresponding fields of the target object
- static
Object.assign method.
The examples below demonstrate the second approach as the most simple and compact.
Copying fields of only those objects that are present in the first array:
var array1 = [ { name: "dima" } ]; var array2 = [ { name: "dima", age: 22, notes: "test0" }, { name: "oleg", age: 27, notes: "test1" }, { name: "vasja", age: 44, notes: "test2" } ]; function objArrMerge(target, source) { const findTargetObj = n => target.find(o => o.name === n); let tObj; for (let i = 0; i < source.length; i++) { if (source[i].name && source[i].name.length && (tObj = findTargetObj(source[i].name))) tObj = Object.assign(tObj, source[i]); } } objArrMerge(array1, array2); document.body.style.cssText = 'font: 14px monospace; white-space: pre;'; document.body.textContent = 'array1:\n' + JSON.stringify(array1, null, 2);
Copying the fields of all objects (if there is no object in the first array, it will be created)
var array1 = [ { name: "dima" } ]; var array2 = [ { name: "dima", age: 22, notes: "test0" }, { name: "oleg", age: 27, notes: "test1" }, { name: "vasja", age: 44, notes: "test2" } ]; array1 = Object.assign(array1, array2); document.body.style.cssText = 'font: 14px monospace; white-space: pre;'; document.body.textContent = 'array1:\n' + JSON.stringify(array1, null, 2);
array2[1]andarray2[2]) - shouldn't they be copied? - yar85