0

I'm trying to use lodash to compare two arrays of objects and return the difference between the two, then adding it to the original data set. Reason being, the new data will contain the same data from the original. For example, I have 3 objects in orgData, and when I request newData, it will contain the same orgData plus one more object.

var orgData = [{
  "id": 1000,
  "title": "First item"
}, {
  "id": 1001,
  "title": "Second item"
}];

var newData = [{
  "id": 1000,
  "title": "First item"
}, {
  "id": 1001,
  "title": "Second item"
}, {
  "id": 1002,
  "title": "Third item"
}];

My only delimiter in comparing is the id which is unique. I've tried the following, but the error I receive is 'Cannot read property of 'id' undefined' which makes sense.

_.filter(orgData, function(o, x) {
  return o.id !== newData[x].id;
}).forEach(function(x) {
  orgData.push(x);
});
hybrid9
  • 2,466
  • 4
  • 24
  • 24
  • This question might help you: http://stackoverflow.com/questions/25764719/update-if-exists-or-add-new-element-to-array-of-objects-elegant-way-in-javascr – benhowdle89 Oct 23 '14 at 13:43
  • It kind of does, but it doesn't help when the newData has a greater or shorter length than the orgData. How would I know to either add the object to the array or remove an object from the array. – hybrid9 Oct 23 '14 at 18:41

2 Answers2

2

Keep track of ids in a separate data structure:

var orgDataIds = [];

_.each(orgData, function(value) {
    orgDataIds.push(value.id);
})

Inspect the id of each object in newData, and add the object to orgData when the corresponding id isn't found in the ids array:

_.each(newData, function(value) {
    var id = value.id;
    if (orgDataIds.indexOf(id) === -1) {
        orgDataIds.push(id);
        orgData.push(value);
    }
})

It's not clear to me when you want to remove objects from an array though. Are you intending to take the intersection of the two arrays?

dug
  • 2,275
  • 1
  • 18
  • 25
0

var orgData = [{ "id": 1000, "title": "First item" }, { "id": 1001, "title": "Second item" }];

var newData = [{ "id": 1000, "title": "First item" }, { "id": 1001, "title": "Second item" }, { "id": 1002, "title": "Third item" }, { "id": 1003, "title": "Forth item" }];

var newArray = _.union(orgData,newDate)

console.log(JSON.stringify(newArray)) // this will return union of this two array