【问题标题】:Adding key-value pairs of object into another object [duplicate]将对象的键值对添加到另一个对象中[重复]
【发布时间】:2018-07-06 13:02:39
【问题描述】:

是否可以在初始化时将特定键值对从一个对象添加到另一个对象?

const a = {
    android: {
        time: null,
        diff: null
   }
};

const b = {
    out:{
       x: null,
       context:{
           state: null,
           value: null,
           "a.android key-value pairs right here: 
            time: null,
            diff: null"
       }
    }
 };

【问题讨论】:

标签: javascript json ecmascript-6


【解决方案1】:

您可以合并两个对象,例如:

Object.assign(b.out.context, a.android)

const a = {
    android: {
        time: null,
        diff: null
   }
};

let b = {
    out:{
       x: null,
       context:{
           state: null,
           value: null,
            time: 1,
            diff: null
       }
    }
 };
 
Object.assign(b.out.context, a.android);
console.log(b);

UPD

如果你想在初始化时这样做,你可以使用 ...(扩展)运算符:

const a = {
    android: {
        time: 1,
        diff: 2
   }
};

let b = {
    out:{
       x: null,
       context:{
           state: null,
           value: null,
           time: 3,
           diff: 4,
           ...a.android
       }
    }
 };
 

console.log(b);

【讨论】:

  • 那么在初始化时没有任何很酷的 ecmascript 语法可以合并?
  • @Jan 它在这里,被称为 SPREAD,它将新属性合并或添加到对象。我已经更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
  • 2022-08-13
  • 2016-02-24
  • 1970-01-01
  • 2017-01-19
  • 2020-11-30
相关资源
最近更新 更多