【问题标题】:how to add nested object with new object [duplicate]如何使用新对象添加嵌套对象[重复]
【发布时间】:2020-02-17 10:36:18
【问题描述】:

实际上,我想将帽子对象添加到服装对象,我不想将对象更改为对象数组。 谁能帮我在我的场景中添加帽子。

const clothing = {
shirts:{
id: 1,
title: 'shirts' ,
item: [
  {
    id: 01,
    name:'plain shirt',
  },
  {
    id: 02,
    name: 'stripe shirt',
  },
 ],
},

tshirt: {
id: 2,
title: 't-shirt',
item: [
  {
    id: 03,
    name: 'plain t-shirt',
  },
  {
    id: 04,
    name: 'stripe t-shirt',
   }
  ],
 },
}

const newClothing = {...clothing};
newClothing[{hats:{id:3, title:'hats', item:[{id:05, name:'blue hats'}]}}];

console.log(newClothing.hats);

【问题讨论】:

  • clothing.hats = 你的帽子。
  • 这能回答你的问题吗? Add new element to an existing object
  • {...clothing}; 一个小警告,这只会做一个浅拷贝,所以如果你期待一个完整的 newClothing 拷贝是行不通的。

标签: javascript json reactjs object


【解决方案1】:

这是最简单的方法:

const newClothing = {...clothing, hats: { ...your hats object here } };

【讨论】:

  • 没问题:) :)
【解决方案2】:

据我了解,我认为您不需要在这里做任何花哨的事情。只需添加如下属性:

clothing.hats = {
    id:3, 
    title:'hats', 
    item:[{id:05, name:'blue hats'}]
   }

【讨论】:

  • 谢谢老哥的回答..已经解决了..
【解决方案3】:

使用 .添加帽子对象的符号

const clothing = {
shirts:{
id: 1,
title: 'shirts' ,
item: [
  {
    id: 01,
    name:'plain shirt',
  },
  {
    id: 02,
    name: 'stripe shirt',
  },
 ],
},

tshirt: {
id: 2,
title: 't-shirt',
item: [
  {
    id: 03,
    name: 'plain t-shirt',
  },
  {
    id: 04,
    name: 'stripe t-shirt',
   }
  ],
 },
}


clothing.hats={id:3, title:'hats', item:[{id:05, name:'blue hats'}]};
console.log(clothing.hats);

【讨论】:

    猜你喜欢
    • 2023-01-12
    • 2018-11-07
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    • 2015-07-27
    • 2012-10-05
    相关资源
    最近更新 更多