Home > Software design >  Add property & value from variable to existing object in JavaScript
Add property & value from variable to existing object in JavaScript

Time:05-02

I am trying to add properties & values from variable to existing object in JavaScript. My code is like below.

var partno = $this.parents('.cart_item').data('partno');
if (localStorage.getItem("shipping_values")) {
  var shipping_values = localStorage.getItem("shipping_values");
  shipping_values[partno] = $this.val();
  console.log(shipping_values); // I am not getting updated values here.
}

CodePudding user response:

Values received from localStorage are in strings. You should run JSON.parse and then add values to object.

var shipping_values = JSON.parse(localStorage.getItem("shipping_values"));
shipping_values[partno] = $this.val();

  • Related