如果我知道其他属性,在数组中查找对象并更改其属性 [英] Find object in array and change its property if I know its other property

查看:110
本文介绍了如果我知道其他属性,在数组中查找对象并更改其属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,我需要一个函数,通过对象属性查找对象数组(例如 id )并更改其他属性(名称在示例中)。目前我的实现如下所示:

I've got an array of objects and I need a function that finds object an array by the objects property (id in example) and changes its other property (name in example). Currently my implementation looks like this:

var arrayOfObjects = [{
    id: 1,
    name: 'Alpha'
}, {
    id: 2,
    name: 'Bravo'
}];

var setNameById = function (id, newName) {
    arrayOfObjects.filter(function(obj) {return obj.id === id;}).name = newName;
};

console.log(JSON.stringify(arrayOfObjects)); // initial array logged
setNameById(2, 'Charlie');
console.log(JSON.stringify(arrayOfObjects)); // initial array logged

我知道问题在于更改过滤器返回的对象和不是初始的,但我没有找到能够在这种情况下访问初始对象的实现,是否可能或者我是否需要重新考虑导致我这一点的步骤。

I understand that the problem is in changing the object that is returned by filter and not initial one, but I haven't found implementations that give access to initial object in such a situation, is it possible or do I need to rethink the steps that led me to this point.

推荐答案

使用此代替过滤器。过滤产生新数组。

Use this instead of filter. Filter produce new array.

arrayOfObjects.forEach(function(v){
  if (v.id == id) {v.name = newName}
});

这篇关于如果我知道其他属性,在数组中查找对象并更改其属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆