How can I update a row in a javascript array based

2019-08-31 18:25发布

我有一个这样的数据的数组:

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加载。

Answer 1:

最简单的方法是刚刚超过环,找到一个具有匹配名称,然后更新年龄:

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例

使用下划线你可以使用_.find方法做的,而不是下面的for循环:

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

的jsfiddle例



Answer 2:

编辑:您可以使用ES6 滤波器箭头功能相结合

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

您可以使用_.where功能

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

然后更新比赛

match[0].age = newage


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

这应该这样做。 它的整洁,可靠和有下划线



Answer 4:

使用下划线你可以使用_.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."}


Answer 5:

您可以使用findWhere和扩展

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


Answer 6:

您可以使用_.find方法,如下所示:

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

工作示例: http://jsfiddle.net/9C2u3/



Answer 7:

var match = _.findWhere(nameInfo , {name  :nametofind });
match.age = newage


Answer 8:

一个staright了利用lodash的发现()函数,

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;

注意:如果有多个莫罗尼对象,_.find只能取的第一场比赛。



文章来源: How can I update a row in a javascript array based on a key value?