Copy array of objects and make changes without modifying original array

后端 未结 4 1384
谎友^
谎友^ 2021-01-18 04:41

I have an array of objects. I would like to deep copy the array of objects and make some changes to each object. I want to do this without modifying the original array or or

4条回答
  •  时光取名叫无心
    2021-01-18 04:47

    For a single pass, you could use Object.assign with the changed property as well.

    const users = [{ id: 1, name: 'Jack', approved: false }, { id: 2, name: 'Bill', approved: true }, { id: 3, name: 'Rick', approved: false }, { id: 4, name: 'Rick', approved: true }];
    const users2 = users.map(u => Object.assign({}, u, { approved: true }));
    
    console.log(users2);
    console.log(users);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题