Le Qs Le Qs - 4 months ago 9
Javascript Question

Adding key/value pair fails with Object assign

I have an object that i am storing in local storage. I would lie 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
. How can i add the item to the existing object?.

Answer

You are successfully changing newdata but then you do not use it. Instead you are calling JSON.parse(retrievedObject) again.

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>