将对象列表中的对象项替换为另一个项

2024-03-18

我的变量中有一个项目对象this.rows。有一个来自服务器的实时项目与里面的项目相同this.rows对象集合。

如何用新值替换项目?

这是一个例子:

    let rows = [
        {id: 11, active: 'no'},
        {id: 22, active: 'yes'},
        {id: 33, active: 'no'},
        {id: 44, active: 'no'}
    ]

    new_item = {id: 22, active:'yeah'};

    rows.forEach(item => {
        if (item.id === new_item.id) {
          return new_item;
        }
    });

使用“findIndex”方法在 rows 数组中查找新项目元素的索引。然后,检查是否找到结果(检查索引是否大于-1)。使用找到的元素的位置将项目分配给数组。

const indexOfItemInArray = rows.findIndex(q => q.id === new_item.id);

if (indexOfItemInArray > -1) {
   rows[indexOfItemInArray] = new_item;
}

或者使用“拼接”方法:

const indexOfItemInArray = rows.findIndex(q => q.id === new_item.id);
rows.splice(indexOfItemInArray, 1, new_item);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将对象列表中的对象项替换为另一个项 的相关文章

随机推荐