Reputation: 973
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));
}
}
}
Upvotes: 6
Views: 25537
Reputation: 21
The Underscore.js library isn't strictly necessary for this specific problem, but it's great for dealing with collections.
var items = [{"Id":"car","color":"blue"},{"Id":"truck","color":"red"}];
var newItem = {"Id":"car","color":"yellow"};
_.each(items, function(item) {
if (item.Id === newItem.Id) item.color = newItem.color
});
Upvotes: 2
Reputation: 1912
Here's a way to do it, using jQuery:
var items = [
{"Id": "car", "color": "blue"},
{"Id": "truck", "color": "red"}
];
var newItem = {
"Id": "car",
"color": "yellow"
};
$(items).each(function(item) {
if ($(this)[0].Id == newItem.Id) {
$(this)[0].color = newItem.color
}
});
Upvotes: 2
Reputation: 18923
The following code should work for you. You can exit the loop once the id is matched. A little better performance wise.
items = [{"Id":"car","color":"blue"},{"Id":"truck","color":"red"}];
newItem = {"Id":"car","color":"yellow"};
for (var i = 0; i < items.length; i++){
if (newItem.id == items[i].id ){
items[i].color = newItem.color;
break;
}
}
Upvotes: 2
Reputation: 1870
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
}
});
Upvotes: 9
Reputation: 9550
Check working demo: JSFiddle.
Using Array.prototype.map
is concise and clear:
items.map(function(obj) {
(obj.Id === newItem.Id) && (obj.color = newItem.color);
});
Upvotes: 2
Reputation: 6676
Try this:
items.forEach(function(item) {
if(item.Id == newItem.Id && item.color != newItem.color){
item.color = newItem.color;
}
});
Upvotes: 4