简体   繁体   中英

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.

 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

 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM