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