微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将对象与objects.assign 结合起来? 注意什么是可变的

如何解决如何将对象与objects.assign 结合起来? 注意什么是可变的

我的简单代码

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',obj1: {},c: '1999' }
[ 'a','b','obj1','c' ]

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

解决方法

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

您还期望什么,我们可以帮助您到达那里吗?

也许您真的打错了,希望第一个对象 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));

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

注意什么是可变的

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

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

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

// 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({},obj2);

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

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

,

我猜你希望 ob1 是 obj2 里面的 obj1

那么这是一种方法:

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

const obj2 = {
  obj1: {},};

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?