Copy array of objects and make changes without modifying original array

后端 未结 4 1350
谎友^
谎友^ 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:04

    I prefer JSON.stringify and JSON.parse

    var 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 } ];
    
    // user2 will be copy of array users without reference
    var users2 = JSON.parse(JSON.stringify(users));
    

提交回复
热议问题