简体   繁体   English

使用对象分配添加键/值对失败

[英]Adding key/value pair fails with Object assign

I have an object that i am storing in local storage. 我有一个对象,我存储在本地存储中。 I would like to retrieve the object and add an key/value item to it. 我想检索对象并向其添加一个键/值项。 This is the code 这是代码

 var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

var newdata = JSON.parse(retrievedObject);
var obj2 = {"four":"4"};
Object.assign(newdata, obj2);

$.each(JSON.parse(retrievedObject), function (index, value) {
  console.log(index+"  "+value);
});

The new item is not added to testObject . 新项目未添加到testObject How can I add the item to the existing object?. 如何将项目添加到现有对象?

You are successfully changing newdata but then you do not use it. 你成功地改变newdata但你不使用它。 Instead you are calling JSON.parse(retrievedObject) again. 而是再次调用JSON.parse(retrievedObject)

 var testObject = { 'one': 1, 'two': 2, 'three': 3 }; // Put the object into storage // Just use a variable because we cant use localstorage on snippet var storage = JSON.stringify(testObject); // Retrieve the object from storage var retrievedObject = storage; var newdata = JSON.parse(retrievedObject); var obj2 = {"four":"4"}; Object.assign(newdata, obj2); $.each(newdata, function (index, value) { console.log(index+" "+value); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

retrievedObject is a string. retrievedObject是一个字符串。 You parse the string, modify the resulting object ( newdata gets modified). 您解析字符串,修改生成的对象( newdata得到修改)。 You should not expect the initial string to change. 您不应该期望更改初始字符串。

In order to update localStorage, just do: 要更新localStorage,只需执行以下操作:

localStorage.setItem('testObject', JSON.stringify(newdata));

Note that after that operation retrievedObject would still be the string with { 'one': 1, 'two': 2, 'three': 3 } 请注意,在该操作之后, retrievedObject仍然是{ 'one': 1, 'two': 2, 'three': 3 }的字符串

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

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