Below are my two arrays. I want to compare them, and the resulting array should contain updated values. Arrays span n levels, i.e. There are no fixed levels.
The first array, i.e. array before update.
var parentArray1=[ { "id": 1, "name": "test", "context": [ { "id": 1.1, "name": "test 1.1" } ] }, { "id": 2, "name": "test" }, { "id": 3, "name": "test", "context": [ { "id": 3.1, "name": "test 3.1" } ] }, { "id": 4, "name": "test" } ]
The operations that I performed are
1. Adding a new item 2. Updating an existing item
As a result of these two operations, I get the changed values ββin another array. i.e.
var changedArray= [ { "id": 1, "name": "test1", "context": [ { "id": 1.1, "name": "Changed test 1.1" } ] }, { "id": 5, "name": "test5" } ]
Now I have written a generic function that goes through parentArray1 and uses unique properties. I need to either add a new item if the item is in a modified Array , or update an existing item at any level
The resulting array should be ...
[ { "id": 1, "name": "test", "context": [ { "id": 1.1, "name": "Changed test 1.1" } ] }, { "id": 2, "name": "test" }, { "id": 3, "name": "test", "context": [ { "id": 3.1, "name": "test 3.1" } ] }, { "id": 4, "name": "test" }, { "id": 5, "name": "test5" } ]
General function:
compareArray(parentArray1, changedArray, ["id"]); function compareArray(array1, array2, propertyArray) { var newItem = new Array(); array2.map(function(a1Item) { array1.map(function(a2Item) { / If array loop again / if (a2Item.constructor === Array) { compareArray(a2Item, a1Item) } else { / loop the property name to validate / propertyArray.map(function(property) { if (a2Item[property]) { if (a2Item[property] === a1Item[property]) { a2Item = a1Item } else { var isAvailable = _.find(newItem, function(item) { return item[property] === a1Item[property] }) if (!isAvailable) { newItem.push(a1Item); } } } }) } }); }); / Insert the new item into the source array / newItem.map(function(item) { array1.push(item); }); console.log("After Compare : " + array1); }