简体   繁体   中英

Javascript approach to copy properties of first array(of objects) into another array(of objects) of different lengths

I have an object array say

srcObj = [{a:1, b:2}, {c:3, d:4}]

destObj = [{a:1, b:2}]

I want to copy values of this array into another array that may have a shorter length than the above srcObj array. How would I construct the loop to increase the length of destObj array depending on the size of srcObj array and then insert the missing items from srcObj array to destObj array.

The following code do the job:

 function containsObject(obj, list) { var i; for (i = 0; i < list.length; i++) { if (JSON.stringify(list[i]) === JSON.stringify(obj)) { return true; } } return false; } var srcObj = [{a:1, b:2}, {c:3, d:4}] var destObj = [{a:1, b:2}] for(var i = 0; i < srcObj.length; i++) { if (!containsObject(srcObj[i], destObj)){ destObj.push(srcObj[i]); } } console.log(destObj); 

If you want a more slow and more generic way to compare objects I recommend you to read the answer for the question: Object comparison in JavaScript

(assuming destObj.length < srcObj.length is already known)

Maybe:

var i;
while ((i = destObj.length) < srcObj.length) {
  destObj.push(srcObj[i]);
}

?

(But note it's just a shallow copy of array items, from srcObj into destObj; the "copied" object values will be in fact shared by the two arrays, by references; and this may or may not be what you want)

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