Let's assume I have two simple objects and I want to create a third one that will be joining their properties. This works perfectly:
(()=>{
const a1 = {a: 2, b: 3}
const b1 = {a: 100, c: 5}
return {...a1, ...b1}
})()
// { a: 100, b: 3, c: 5 }
But it stops working once I try to create a new object derived from b1 using .reduce
. For a sake of simplicity let's create a reduce function that simply makes a shallow copy of the b1 object:
let r = (()=>{ const a1 = {a: 2, b: 3} const b1 = {a: 100, c: 5}, b2 = Object.entries(b1).reduce((acc, [key, value])=>Object.defineProperty(acc, key, {value}), {}) console.log(b2) // {a: 100 c: 5} return {...a1, ...b2} })() console.log(r);// { a: 2, b: 3 }
I have a feeling that there is something about .reduce
function that I just don't understand. What can I do to fix this?
By default, properties created with defineProperty
are not enumerable, so they won't be included with a spread.
To fix:
b2 = Object.entries(b1).reduce((acc, [key, value]) =>
Object.defineProperty(acc, key, {value, enumerable: true})
, {})
You should mark the property as enumerable
Object.defineProperty(acc, key, {value, enumerable: true});
Why not just using the function Object.assign
instead, it's straightforward.
let r = (()=> { const a1 = {a: 2, b: 3}; const b1 = {a: 100, c: 5}; const b2 = Object.entries(b1).reduce((acc, [key, value]) => Object.assign(acc, {[key]: value}), {}) console.log(b2); // {a: 100 c: 5} return {...a1, ...b2} })() console.log(r); // { a: 2, b: 3 }
One fix could be to use Object.assign
to create a copy of b1
like:
let r = (()=>{ const a1 = {a: 2, b: 3} const b1 = {a: 100, c: 5} const b2 = Object.assign({}, b1) console.log(b2) // {a: 100 c: 5} return {...a1, ...b2} })() console.log(r); // { a: 100, b: 3, c: 5 }
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.