Skip to content Skip to sidebar Skip to footer

How Can I Update A Row In A Javascript Array Based On A Key Value?

I have an array of data like this: var nameInfo = [{name: 'Moroni', age: 50}, {name: 'Tiancum', age: 43}, {name: 'Jacob', age: 27},

Solution 1:

Easiest way is to just loop over and find the one with a matching name then update the age:

var newNameInfo  = {name: "Moroni", age: 51};
var name = newNameInfo.name;

for (var i = 0, l = nameInfo.length; i < l; i++) {
    if (nameInfo[i].name === name) {
        nameInfo[i].age = newNameInfo.age;
        break;
    }
}

JSFiddle Example

Using underscore you can use the _.find method to do the following instead of the for loop:

var match = _.find(nameInfo, function(item) { return item.name === name })
if (match) {
    match.age = newNameInfo.age;
}

JSFiddle Example

Solution 2:

Edit: You can use ES6 filter combined with arrow functions

nameInfo.filter(x => {return x.name === nametofind })[0].age = newage

You can use _.where function

var match = _.where(nameInfo , {name  :nametofind });

then update the match

match[0].age = newage

Solution 3:

var nameInfo  = [{name: "Moroni", age: 50},{name: "Tiancum", age: 43},
                 {name: "Jacob", age: 27},{name: "Nephi", age: 29},
                 {name: "Enos", age: 34}
                ];
_.map(nameInfo, function(obj){
  if(obj.name=='Moroni') {
    obj.age=51; // Or replace the whole obj
  }
});

This should do it. It's neat and reliable and with underscore

Solution 4:

Using Underscore you can use _.findWhere http://underscorejs.org/#findWhere

_.findWhere(publicServicePulitzers, {newsroom:"The New York Times"});
=> {year:1918, newsroom:"The New York Times",
  reason:"For its public service in publishing in full so many official reports,
  documents and speeches by European statesmen relating to the progress and
  conduct of the war."}

Solution 5:

You can use findWhere and extend

obj = _.findWhere(@songs, {id: id})
_.extend(obj, {name:'foo', age:12});

Post a Comment for "How Can I Update A Row In A Javascript Array Based On A Key Value?"