Reputation: 701
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?
Upvotes: 1
Views: 834
Reputation: 363
try this with javascript higher order functions:
arr.map(function(item){
item["segmentId"] = obj[item["name"]]["segmentId"]
});
Upvotes: 2
Reputation:
Although you have not provided a fiddle.But you can do it in jquery like below:
Please note I am creating a new array for the result set.
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": "69",
"November 2015": "3454",
"December 2015": "345"
}
};
var a=[];
$.each(arr, function(i, v) {
$.each(obj, function(oi, ov) {
if(arr[i].name==oi)
a.push(obj[oi].segmentId);
});
});
alert(a.length);
Upvotes: 0