I have following array which consist of json objects:
items = [{"Id":"car","color":"blue"},{"Id":"truck","color":"red"}]
I have new json object. If the "Id" of this object(newItem) matches the "Id" in items, i would like to replace the "color" value.
newItem = {"Id":"car","color":"yellow"}
So, i would like output like this:
items = [{"Id":"car","color":"yellow"},{"Id":"truck","color":"red"}]
Here's what i have so far:
for (var i=0; i<items.length; i++) {
var x = items[i];
if(x.Id == newItem.Id){ //first check if id matches
if (JSON.stringify(items[i]) == JSON.stringify(newItem)) {
alert('objects are same');
return ;
}
else {
var newColor = JSON.stringify(x).replace(x.color, newItem.color);
alert(JSON.parse(newColor));
}
}
}
Working JSFiddle. Here's one way to do it by using .forEach
from Array.prototype.forEach:
var items = [{"Id":"car","color":"blue"},{"Id":"truck","color":"red"}];
var newItem = {"Id":"car","color":"yellow"}
items.forEach(function(item) {
if (newItem.Id === item.Id) {
item.color = newItem.color
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With