用另一个项目替换对象列表中的一个对象项目 [英] Replace an object item in object list with another item

查看:46
本文介绍了用另一个项目替换对象列表中的一个对象项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的变量this.rows中有一个项目对象.服务器中有一个实时项目,它与this.rows对象集合中的实时项目相同.

I have an object of items in my variable this.rows. There is a real-time item coming from the server which is identical to one which is inside in this.rows object collection.

如何用新值替换项目?

这里是一个例子:

    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).使用找到的元素的位置将项目分配给数组.

Use the "findIndex" method to look for the index of the new item element in the rows array. Afterwards, check if a result was found (check if the index is greater than -1). Assign the item to the array using the position of the found element.

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

这篇关于用另一个项目替换对象列表中的一个对象项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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