【问题标题】:How to combine objects with objects.assign?如何将对象与objects.assign结合起来?
【发布时间】:2021-06-03 21:15:32
【问题描述】:

我的简单代码

const ob1 = {
  a: 'pokushevski',
  b: '2001',
};

const obj2 = {
  obj1: {},
  c: '1999',
};

const result = Object.assign(ob1, obj2);
console.log(result);
console.log(Object.getOwnPropertyNames(result));

输出

{ a: 'pokushevski', b: '2001', obj1: {}, c: '1999' }
[ 'a', 'b', 'obj1', 'c' ]

结果中的obj1 似乎与任何其他属性一样,没有对const obj1 的任何引用。 为什么?

【问题讨论】:

  • Object.assign() 改变第一个参数的对象,你应该使用对象销毁/传播:const result = { ...obj1, ...obj2 };
  • 你能告诉我们你的预期输出是什么吗?
  • @HaoWu 这个不行,你自己试试吧。
  • const result = { ...obj2, ...{ obj1 } }; 也许这就是你想要的

标签: javascript ecmascript-2016


【解决方案1】:

您现在所做的基本上是将ob1(不带'j')与obj2(带'j')合并,因为obj1(带'j')是@内的一个空对象987654324@,它被添加为结果合并对象的属性。

您还有什么期望,我们可以帮助您实现吗?

也许您实际上打错了字,希望将第一个对象ob1 命名为obj1,然后用作obj2 中的属性,最后合并这两个对象?

如果是这样,你会这样做:

const obj1 = {
  a: 'pokushevski',
  b: '2001',
};

const obj2 = {
  obj1, // shorthand syntax, property will be named the same as the const
  c: '1999',
};

// avoid mutation by using a new object as the target
const result = Object.assign({}, obj1, obj2);

// Display result and property names
console.log(result);
console.log(Object.getOwnPropertyNames(result));

如果您只想在obj2 中添加obj1,则不需要Object.assign

注意什么是可变的

使用上面的代码,每当您更新 result.obj1 属性时,原始的 obj1 都会被修改。尝试更新result.obj1.a 然后console.log(obj1)

如果你想防止这种情况,你可以像这样使用解构:

const obj1 = {
  a: 'pokushevski',
  b: '2001',
};

// Create a shallow copy of `obj1` to prevent mutating the original
// object by updating `obj2.obj1` properties
const obj2 = {
  obj1: {...obj1},
  c: '1999',
};

// Avoid mutating the original `obj1` by using a new object as the target
const result = Object.assign({}, obj1, obj2);

// Display result and property names
console.log(result);
console.log(Object.getOwnPropertyNames(result))

如果您真的想继续使用 Object.assign 而不是解构,您可以将 obj1: {...obj1} 替换为 obj1: Object.assign({}, obj1)

【讨论】:

  • 如何将obj插入obj2?
  • 根据我的理解更新了答案
  • 是的,打错字了。
  • 从 OP 似乎问的内容来看,他期待 result 的以下结构:{ a: 'pokushevski', b: '2001', obj1: {a: 'pokushevski', b: '2001'}, c: '1999' }
  • 很抱歉给您带来麻烦。我想我明白了。非常感谢你的解释:)
【解决方案2】:

我猜你希望 ob1 在 obj2 中成为 obj1

那么这是一种方法:

const ob1 = {
  a: 'pokushevski',
  b: '2001',
};

const obj2 = {
  obj1: {},
  c: '1999',
};

const result = Object.assign({}, obj2);
Object.assign(result.obj1, ob1);
console.log(result);
console.log(Object.getOwnPropertyNames(result));

【讨论】:

  • 这是一种非常奇怪的方法!为什么要分配?
  • 因为问题的标题是“How to combine objects with objects.assign?”
  • 我想这一切都归结为可变的 OP 希望他的原始ob1(或obj1)是:)
猜你喜欢
  • 2010-09-25
  • 1970-01-01
  • 1970-01-01
  • 2019-10-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-08
  • 2012-03-17
  • 2017-12-15
相关资源
最近更新 更多