I've an array and an object. I should compare the Array value with the object key. If both are matches, I should push the value of object into the array.
I've achieve this with the below logic.
var arr = [{ "name": "Coal", "segmentId": null }, { "name": "Ash", "segmentId": null }];
var obj = {
"Ash": {
"October 2015": "66",
"segmentId": "66",
"December 2015": "435",
"November 2015": "34535"
},
"Coal": {
"October 2015": "23455",
"segmentId": "66",
"November 2015": "3454",
"December 2015": "345"
}
};
document.writeln("Original Array : " + JSON.stringify(arr));
for (var i = 0; i < arr.length; i++) {
var keys = Object.keys(obj);
for (var j = 0; j < keys.length; j++) {
if (arr[i].name === keys[j]) {
arr[i].segmentId = obj[keys[j]].segmentId;
}
}
}
document.writeln("Transformed Array : " + JSON.stringify(arr));
I would like to know, Is there any other best way to handle this or any js library to make it simple?