Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace value if key is same in json object

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));

        }
    }            
}
like image 861
user3399326 Avatar asked Jul 30 '15 18:07

user3399326


1 Answers

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
  }
});
like image 77
Pavan Ravipati Avatar answered Sep 28 '22 20:09

Pavan Ravipati