简体   繁体   English

减少和 object 解构/赋值

[英]Reduce and object deconstruction/assignment

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 .但是一旦我尝试使用.reduce创建一个从 b1 派生的新的 object ,它就会停止工作。 For a sake of simplicity let's create a reduce function that simply makes a shallow copy of the b1 object:为了简单起见,让我们创建一个 reduce function,它只是制作 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.我有一种感觉,关于.reduce function 有一些我不明白的地方。 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.默认情况下,使用defineProperty创建的属性是不可枚举的,因此它们不会包含在传播中。

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.为什么不直接使用 function Object.assign ,它很简单。

 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:一种解决方法是使用Object.assign创建b1的副本,例如:

 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 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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