1

I have two arrays like

var array1 = [
    {
      id: '1',
      name: 'test'
    },
    {
      id: '2',
      name: 'test2'
    },
    {
      id: '3',
      name: 'test3'
    }
]

var array2=[
    {
      id: '2',
      name: 'test2'
    }
]

I want to loop through array 1 and find the same object and add more property in array 1

I have something like

 for(var i=0; i < array1.length; i++) {
     if(array2[i].id == array1[i].id){
         alert('find!')
     } 
 }

I understand my above codes don't work because the index is different. Can someone help me about this issue? Thanks a lot!

FlyingCat
  • 14,036
  • 36
  • 119
  • 198

2 Answers2

1

It’s time for ECMA5

var array1 = [
    {
      id: '1',
      name: 'test',
      foo: {
        bar: 'bar',
        quux: 'quux'
      }
    },
    {
      id: '2',
      name: 'test2'
    },
    {
      id: '3',
      name: 'test3'
    }
];

function equal(objA, objB) {
    if(Object.keys(objA).length !== Object.keys(objB).length) {
        return false;
    }

    var areEqual = Object.keys(objA).every(function(key) {
        if(typeof objA[key] === "object") {
            return equal(objA[key], objB[key]);
        }
        return objA[key] === objB[key];
    });

    return  areEqual;
}

function hasElement(array, element) {
    return array.some(function(el) {
        return equal(el, element);
    });
}

console.log(hasElement(array1, {
  id: '1',
  name: 'test',
  foo: {
    bar: 'bar',
        quux: 'quux'
    }
}));
Krzysztof Safjanowski
  • 7,292
  • 3
  • 35
  • 47
0

Assuming the IDs in array2 are all unique, I would create an object whose keys are the IDs:

var obj2 = {};
for (var i = 0; i < array2.length; i++) {
    obj2[array2[i].id] = array2[i];
}

Then I would use this to find matching elements:

for (var i = 0; i < array1.length; i++) {
    if (obj2[array1[i].id]) {
        alert("find!");
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612