JavaScript - copy array of objects and make changes without modifying original array
我有一组对象。我想深入复制对象数组并对每个对象进行一些更改。我想在不修改原始数组或该数组中的原始对象的情况下执行此操作。
我就是这样做的。但是,作为一个新手,我想确保这是一个很好的方法。
有更好的方法吗?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | 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) => { return Object.assign({}, u); } ) .map( (u) => { u.approved = true; return u; } ); console.log('New users2 array of objects:') console.log(users2); console.log('This was original users array is untouched:') console.log(users); |
输出:
1 2 3 4 5 6 7 8 9 10 | New users2 array of objects: [ { id: 1, name: 'Jack', approved: true }, { id: 2, name: 'Bill', approved: true }, { id: 3, name: 'Rick', approved: true }, { id: 4, name: 'Rick', approved: true } ] This was original users array is untouched: [ { id: 1, name: 'Jack', approved: false }, { id: 2, name: 'Bill', approved: true }, { id: 3, name: 'Rick', approved: false }, { id: 4, name: 'Rick', approved: true } ] |
对于单程,您也可以将
1 2 3 4 5 | 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); |
1 | .as-console-wrapper { max-height: 100% !important; top: 0; } |
是的,看起来不错。您还可以在克隆时执行修改,以避免在阵列上映射两次。
1 2 3 4 5 | const users2 = users.map((u) => { const copiedUser = Object.assign({}, u); copiedUser.approved = true; return copiedUser; }); |
我更喜欢json.stringify和json.parse
1 2 3 4 5 6 7 | 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)); |
有几种方法可以用javascript复制数组,我认为最常用的是:
- 切片()
- 数组(从)
slice函数将返回给定数组的一部分(或所有内容)作为新数组,基于开始和结束索引(开始和结束索引是可选的):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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()是一个函数,它将从类似数组的参数或iterable参数创建一个新的数组。
1 2 3 4 5 | 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"] |
关于切片的更多信息
有关array.from()的详细信息