Replace an object item in object list with another item

南楼画角 提交于 2019-12-24 11:50:36

问题


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.

How to I replace an item with a new values ?

Here is an example:

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

回答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;
}

Or use the "splice" method:

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



回答2:


find item in rows and assign new item keys:

mutate rows:

_.chain(rows)
    .find({ id: new_item.id })
    .assign(new_item)
    .value();

do not mutate rows:

const newRows = _.chain(rows)
    .findIndex({ id: new_item.id })
    .thru(index => _.chain(rows)
        .cloneDeep()
        .set(index, new_item)
        .value()
    )
    .value();



回答3:


To update easilly your array with a new value for specific id, use the map function :

rows = rows.map((row) => {
    if (row.id === new_item.id) {
        row = new_item;
    }

    return row;
});


来源:https://stackoverflow.com/questions/48151692/replace-an-object-item-in-object-list-with-another-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!