Javascript ES6/ES5 find in array and change

前端 未结 8 1316
后悔当初
后悔当初 2020-12-12 10:52

I have an array of objects. I want to find by some field, and then to change it:

var item = {...}
var items = [{id:2}, {id:2}, {id:2}];

var foundItem = item         


        
8条回答
  •  时光取名叫无心
    2020-12-12 11:12

    May be use Filter.

    const list = [{id:0}, {id:1}, {id:2}];
    let listCopy = [...list];
    let filteredDataSource = listCopy.filter((item) => {
           if (item.id === 1) {
               item.id = 12345;
            }
    
            return item;
        });
    console.log(filteredDataSource);
    

    Array [Object { id: 0 }, Object { id: 12345 }, Object { id: 2 }]

提交回复
热议问题