2

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.

neelmeg
  • 2,459
  • 6
  • 34
  • 46
  • `destObj.length = srcObj.length` ? – Rayon Mar 10 '16 at 05:01
  • 2
    Does the destination array hold references to the same objects that are in the source, or are they duplicate objects that have all the same property names and values? – nnnnnn Mar 10 '16 at 05:07
  • They are duplicate objects that has property names that match the source object. It may have additional property names too.. – neelmeg Mar 10 '16 at 06:15

2 Answers2

0

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

Community
  • 1
  • 1
Felipe Plets
  • 7,230
  • 3
  • 36
  • 60
0

(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)

YSharp
  • 1,066
  • 9
  • 8