我有一个对象数组。我想深度复制对象数组并对每个对象进行一些更改。我想这样做而不修改原始数组或该数组中的原始对象。
这就是我做的方式。但是,作为JavaScript的新手,我想确保这是一个很好的方法。
有更好的方法吗?
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);
输出:
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 } ]
答案 0 :(得分:8)
对于单次传递,您也可以将Object.assign
与更改的属性一起使用。
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; }

答案 1 :(得分:3)
是的,看起来不错。您还可以在克隆时执行修改,以避免在阵列上映射两次。
const users2 = users.map((u) => {
const copiedUser = Object.assign({}, u);
copiedUser.approved = true;
return copiedUser;
});
答案 2 :(得分:1)
有几种方法可以在javascript中复制数组,我相信最常用的是:
slice函数将返回给定数组的一部分(或所有内容)作为新数组,基于开始和结束索引(开始和结束索引是可选的):
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()是一个函数,它将从类似数组或可迭代的参数创建一个新数组。
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"]
答案 3 :(得分:1)
我更喜欢JSON.stringify和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));