gpt4 book ai didi

javascript - 使用传播语法在 ES6 中进行深度复制

转载 作者:IT王子 更新时间:2023-10-29 02:48:49 25 4
gpt4 key购买 nike

我正在尝试为我的 Redux 项目创建一个深度复制映射方法,该方法将使用对象而不是数组。我读到,在 Redux 中,每个状态都不应该改变之前状态的任何内容。

export const mapCopy = (object, callback) => {
return Object.keys(object).reduce(function (output, key) {

output[key] = callback.call(this, {...object[key]});

return output;
},
{});
}

有效:

return mapCopy(state, e => {

if (e.id === action.id) {
e.title = 'new item';
}

return e;
})

但是它不会深度复制内部项目,因此我需要将其调整为:

export const mapCopy = (object, callback) => {
return Object.keys(object).reduce(function (output, key) {

let newObject = {...object[key]};
newObject.style = {...newObject.style};
newObject.data = {...newObject.data};

output[key] = callback.call(this, newObject);

return output;
}, {});
}

这不太优雅,因为它需要知道传递了哪些对象。ES6 中有没有一种方法可以使用扩展语法来深拷贝一个对象?

最佳答案

使用JSON进行深拷贝

var newObject = JSON.parse(JSON.stringify(oldObject))

var oldObject = {
name: 'A',
address: {
street: 'Station Road',
city: 'Pune'
}
}
var newObject = JSON.parse(JSON.stringify(oldObject));

newObject.address.city = 'Delhi';
console.log('newObject');
console.log(newObject);
console.log('oldObject');
console.log(oldObject);

关于javascript - 使用传播语法在 ES6 中进行深度复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38416020/

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