【问题标题】:Push an object into an existing object将对象推入现有对象
【发布时间】:2021-02-14 17:35:49
【问题描述】:

我有一个现有对象,我想将一个新对象推入其中,但没有可定位的属性

例如:

  existingObj = { data: {postion: 1 } };
  objToPush = { person: [{ name: "Bella", age: 100}], about: { height: "1.70", weight: "170"} }

  end up with existingObj = { data: {postion: 1 }, person: [{ name: "Bella", age: 100}], about: { height: "1.70", weight: "170"} }

所以我想将objTopush 添加到existingObj 中,但是existingObj 中没有要定位的属性

【问题讨论】:

  • let newObj = Object.assign({}, existingObj, objToPush); Docs
  • 我可以使用扩展运算符吗?
  • 如果这让你感觉良好。
  • 你想改变原版吗?
  • @charlietfl 是的

标签: javascript object javascript-objects


【解决方案1】:

您可以使用展开语法。

const existingObj = { data: { postion: 1 } };
const objToPush = {
  person: [{ name: 'Bella', age: 100 }],
  about: { height: '1.70', weight: '170' },
};
const ret = { ...existingObj, ...objToPush };
console.log(ret);

【讨论】:

    猜你喜欢
    • 2017-12-05
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多