Copy array of objects and make changes without modifying original array

后端 未结 4 1349
谎友^
谎友^ 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; }

    0 讨论(0)
  • 2021-01-18 04:54

    There are a few ways to copy a array in javascript, i believed that the most used are:

    • slice()
    • Array.from()

    The slice function will return a portion (or all content) of a given array as a new array, based at a begin and end index (begin and end index are optional):

    const a = [1,2,3,4,5,6,7,8,9]
    /*
    * Only begin index
    */
    const b = a.slice(2)
    console.log(b) //Will Print [3,4,5,6,7,8,9]
    /*
    * Begin index and end index
    */
    const c = a.slice(5,8)
    console.log(c) //Will Print [6,7,8]
    /*
    * No indexes provided
    */
    const d = a.slice()
    console.log(d) //Will print [1,2,3,4,5,6,7,8,9]

    Array.from() is a function that will create a new array from an array-like or iterable parameters.

    const a = Array.from('bar');
    console.log(a) //Will Print ["b","a","r"]
    const b = ["for","bar"];
    const c = Array.from(b);
    console.log(c) //Will print  ["for","bar"]

    More about slice

    More about Array.from()

    0 讨论(0)
  • 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));
    
    0 讨论(0)
  • 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;
    }); 
    
    0 讨论(0)
提交回复
热议问题