[英]Update nested array immutably
I'm trying to update a nested array immutably, but I get referential equality between the two results.我正在尝试不可变地更新嵌套数组,但我得到两个结果之间的引用相等。
I'm expecting updated.a.== obj.a
but I'm seeing in the console that they are equal.我期待updated.a.== obj.a
但我在控制台中看到它们是平等的。
function update(dest, source) { return Object.entries(source).reduce((acc, [key, val]) => { if (Array.isArray(val)) { acc[key] = [...val]; } else if (isPlainObject(val)) { acc[key] = {...update(dest[key], source[key]) }; } else { acc[key] = val; } return acc; }, dest); } function isPlainObject(obj) { return Object.prototype.toString.call(obj) === '[object Object]'; } const obj = { a: [1, 2], }; const updated = update(obj, { a: [1, 2] }); console.log(updated.a === obj.a);
Just create a new copy of dest
object using Object.create
只需使用Object.create
创建dest
object 的新副本
function update(dest, source) { return Object.entries(source).reduce((acc, [key, val]) => { if (Array.isArray(val)) { acc[key] = [...val]; } else if (isPlainObject(val)) { acc[key] = {...update(dest[key], source[key]) }; } else { acc[key] = val; } return acc; }, Object.create(dest)); } function isPlainObject(obj) { return Object.prototype.toString.call(obj) === '[object Object]'; } const obj = { a: [1, 2], }; const updated = update(obj, { a: [1, 2] }); console.log(updated.a === obj.a);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.