Monday, June 3, 2024
85
rated 0 times [  86] [ 1]  / answers: 1 / hits: 32055  / 11 Years ago, mon, april 22, 2013, 12:00:00

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.


More From » underscore.js

 Answers
11

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


[#78720] Sunday, April 21, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
raymondd

Total Points: 620
Total Questions: 112
Total Answers: 94

Location: Namibia
Member since Mon, Feb 21, 2022
2 Years ago
raymondd questions
Thu, Apr 22, 21, 00:00, 3 Years ago
Thu, Jul 9, 20, 00:00, 4 Years ago
Thu, Apr 9, 20, 00:00, 4 Years ago
Thu, Jul 25, 19, 00:00, 5 Years ago
;