Copy array of objects and make changes without modifying original array

后端 未结 4 1352
谎友^
谎友^ 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 05:11

    Yes that looks good. You could also perform the modification when you are cloning, in order to avoid mapping over the array twice.

    const users2 = users.map((u) => {
        const copiedUser = Object.assign({}, u);
        copiedUser.approved = true;
        return copiedUser;
    }); 
    

提交回复
热议问题