20

I have an array of data like this:

var nameInfo  = [{name: "Moroni", age: 50},
                 {name: "Tiancum", age: 43},
                 {name: "Jacob", age: 27},
                 {name: "Nephi", age: 29},
                 {name: "Enos", age: 34}];

If I have an object like this:

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

Is there a simple way that I can update the variable nameInfo. The key between these is the name column. I know there is a way that I could do this by searching for the row, removing and adding but I would like to have a way to do this where I updated the row. Note that if it helps I do have underscore.js loaded.

5
  • So the names are unique? Then why aren’t they the names for your object properties in the first place? Commented Apr 22, 2013 at 13:24
  • Yeah I am sorry I should have mentioned. The names are unique. Commented Apr 22, 2013 at 13:48
  • Well then I’d build the whole thing up in the form {"Moroni":{"age":51}} – so you can check for existence of an entry by name without having to loop over all entries. Commented Apr 22, 2013 at 14:05
  • 1
    Book of Mormon names, that's cool! Commented Sep 23, 2015 at 3:53
  • Possible duplicate of How to update array value javascript? Commented Apr 17, 2019 at 10:19

8 Answers 8

29

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

Sign up to request clarification or add additional context in comments.

2 Comments

In the underscore example, i see you declared a new variable called "match" in which you have saved the outcome of _.find. Now you updated that "match" variable with the updated data. How does the original array which is "nameInfo" got updated. I am little new to underscore.
@Achyut The variable match is a reference to the relevant item in the original array, not a copy. So updates to this are also updates to the original item.
12

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

Comments

6
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

1 Comment

Don't you need to return obj in the transformation function? Otherwise you'll get an array of undefined elements.
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."}

Comments

4

You can use findWhere and extend

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

Comments

1

You can use the _.find method, like this:

var nameInfos  = [{name: "Moroni", age: 50},
                 {name: "Tiancum", age: 43},
                 {name: "Jacob", age: 27},
                 {name: "Nephi", age: 29},
                 {name: "Enos", age: 34}];
var nameToSearch = "Moroni";
var myRecord = _.find(nameInfos, function(record){ return record.name === nameToSearch; });

Working example: http://jsfiddle.net/9C2u3/

1 Comment

What if value is not present ! wont his return undefined ? I feel this isnt h best way to deal with this ?
1
var match = _.findWhere(nameInfo , {name  :nametofind });
match.age = newage

1 Comment

` _.findWhere` would not be sufficient in this senario as it matches all key value pairs
1

A staright forward using lodash's find() function,

var nameInfo  = [{name: "Moroni", age: 50},
             {name: "Tiancum", age: 43},
             {name: "Jacob", age: 27},
             {name: "Nephi", age: 29},
             {name: "Enos", age: 34}];

var objToUpdate = _.find(nameInfo, {name: "Moroni"});

if(objToUpdate) objToUpdate.age = 51;

console.log(nameInfo); // Moroni age will be 51;

Note: If there are multiple Moroni objects, _.find can fetch the first match only.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.