gpt4 book ai didi

javascript - 防止通过引用分配

转载 作者:行者123 更新时间:2023-11-29 10:29:08 24 4
gpt4 key购买 nike

我正在尝试根据某些属性在数组中克隆一些对象。

给定一个对象数组:

[
{
id: 1,
data: {
user:
{
user1: 0,
user2: 1,
}
}
},
{
id: 2,
data: {
user:
{
user1: 0,
}
}
},
]

我想把上面的转换成:

[
{
id: 1,
data: {
user: 'user1',
user_status: 0
}
},
{
id: 1,
data: {
user: 'user2',
user_status: 1,
}
},
{
id: 2,
data: {
user: 'user1',
user_status: 0,
}
},
]

无论user 对象中有多少属性,数组中的每个user 对象都应该转换其user 属性。 data 对象中还有其他我想复制但不想修改的属性。

我得到的最接近的是:

result.rows.forEach((item, index) => {

for ( const user in item.data.user ) {
const notif = Object.assign({}, item);
notif.data.user = user;
notif.data.user_status = item.data.user[user];
result.rows.push(notif);
}

});

但是,上面的行为就好像 notif 它是由引用(?)分配的并且正在改变原始对象。在 for in 循环期间使用 console.log 会导致:

console.log(notif.id, notif.data.user, notif.data.user_status)
// Results in 1, user1, undefined
console.log(item.data.user, item.data.user[user])
// Results in user1, undefined instead of the expect { 'user1': 0 }

这会产生如下数组:

{
id: 1,
data: {
user: 'user2', // Should be user1
user_status: undefined, // Should be 0
}
},
{
id: 1,
data: {
user: 'user2', // Should be user2 -- hooray but in a bad way
user_status: undefined, // Should be 1
}
}

所有这些都在 Node.js (8.11.1) 服务器上运行。

最佳答案

item 中的 data 引用了原始的 data 对象,因为 Object.assign 给出了一个浅表克隆,不是深度克隆。

这可能会通过 reduce 一次性进入数组,立即提取所有基元,而不是尝试使用(通过引用)对象来最优雅地实现:

const input=[{id:1,data:{user:{user1:0,user2:1,}}},{id:2,data:{user:{user1:0,}}},]

const output = input.reduce((a, { id, data: { user: users }}) => {
Object.entries(users).forEach(([user, user_status]) => {
a.push({ id, data: { user, user_status }});
});
return a;
}, []);

console.log(output);

对原始代码的修复也将涉及克隆 data 属性:

const input=[{id:1,data:{user:{user1:0,user2:1,}}},{id:2,data:{user:{user1:0,}}},]
const output = [];

input.forEach((item, index) => {
for (const user in item.data.user) {
const notif = Object.assign({}, item);
notif.data = Object.assign({}, item.data);
notif.data.user = user;
notif.data.user_status = item.data.user[user];
output.push(notif);
}

});

console.log(output);

关于javascript - 防止通过引用分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50978634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com