如何根据键值更新javascript数组中的行? [英] How can I update a row in a javascript array based on a key value?
问题描述
我有这样的数据数组:
var nameInfo = [{name: "Moroni", age: 50},
{name: "Tiancum", age: 43},
{name: "Jacob", age: 27},
{name: "Nephi", age: 29},
{name: "Enos", age: 34}];
如果我有这样的对象:
var nameInfo = {name: "Moroni", age: 51};
有没有一种简单的方法可以更新变量nameInfo。这些之间的关键
是名称列。我知道有一种方法,我可以通过搜索行,删除和添加
来做到这一点,但我希望
有办法在我更新行的地方做到这一点。请注意,如果它有帮助我确实加载了underscore.js.
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.
推荐答案
最简单的方法就是循环找到一个匹配的名称然后更新年龄:
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;
}
}
使用下划线可以使用 _。找到方法来执行以下操作而不是for循环:
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;
}
这篇关于如何根据键值更新javascript数组中的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!