简体   繁体   English

如何使用 Object.assign 更新嵌套对象

[英]How to use Object.assign to update an nested object

I want to use Object.assign overwrite a nested object within an object.我想使用Object.assign覆盖对象内的嵌套对象。

for example if I have an object like例如,如果我有一个像

let obj = {2: {fruit: "orange", animal: "dog"} 3: {fruit: "apple", animal: "cat"}}

How would I use Object.assign to update for example the second object with key 3 to {fruit: "banana", animal: "pig"} but still maintain the structure of obj ?我将如何使用Object.assign将例如带有键3的第二个对象更新为{fruit: "banana", animal: "pig"}但仍保持obj的结构?

This solution should be dynamic so if for example the next time, the first object with key 2 could be updated to {fruit: "strawberry", animal: "bat"}此解决方案应该是动态的,例如,如果下次,第一个键为2对象可以更新为{fruit: "strawberry", animal: "bat"}

EDIT编辑

So the new returned object will be所以新返回的对象将是

{2: {fruit: "orange", animal: "dog"} 3: {fruit: "banana", animal: "pig"}}

EDIT2编辑2

Solution needs to be dynamic解决方案需要是动态的

EDIT3编辑3

Seems as though this can't be achieved with just Object.assign so is there a deep copy solution to do this?似乎仅通过Object.assign无法实现这一点,那么是否有深度复制解决方案来做到这一点?

First thing to do is not call your object "Object":首先要做的不是将您的对象称为“对象”:

let obj = {2: {fruit: "orange", animal: "dog"} 3: {fruit: "apple", animal: "cat"}};

Then you can use Object.assign() on obj[3] :然后你可以在obj[3]上使用Object.assign()

Object.assign(obj[3], {fruit: "banana", animal: "pig"});

(If you use "Object" as a variable name, you lose access to the global "Object", making Object.assign impossible to use.) (如果您使用“Object”作为变量名,您将无法访问全局“Object”,从而无法使用Object.assign 。)

If you want a whole new object, you'll have to make copies of the nested objects because Object.assign() performs a shallow copy only.如果您想要一个全新的对象,则必须制作嵌套对象的副本,因为Object.assign()仅执行浅拷贝 In your case that's pretty easy, but in general making a deep copy can be very complicated:在您的情况下,这很容易,但通常制作深层副本可能非常复杂:

let newObj = {
  2: Object.assign({}, obj[2]),
  3: {fruit: "banana", animal: "pig"}
};

Try this below:试试这个:

let data = {2: {fruit: "orange", animal: "dog"} 3: {fruit: "apple", animal: "cat"}}

Object.assign(data[3], {fruit: "banana", animal: "pig"});

console.log(data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM