0

I have a local storage key in the form of a string. Here's how it looks :

var key = localStorage.getItem(localStorage.key(0));
console.log(key);

Above console prints :

 {"logged_user":"myname","abcDatatitle":"AHarmbca Reports","abcData":"300"};

Just FYI : console.log(typeof key); prints string

I want to remove this part "abcDatatitle":"AHarmbca Reports" so that the key (console.log(key);) would look like the following :

{"logged_user":"myname","abcData":"300"};

I could use the replace function of javascript like this,

key = key.replace("abcDatatitle",""); 

but this would remove only this abcDatatitle part. How can I make sure that the whole part "abcDatatitle":"AHarmbca Reports" is gone considering the fact that this value AHarmbca Reports is a dynamic value.

John
  • 1,210
  • 5
  • 23
  • 51
  • Possible duplicate of [How do I remove a property from a JavaScript object?](https://stackoverflow.com/questions/208105/how-do-i-remove-a-property-from-a-javascript-object) – Reactgular Jan 03 '19 at 15:24
  • This is not an object but string. – John Jan 03 '19 at 15:24

3 Answers3

1

You could use delete

For example

var myObject = {"logged_user":"myname","abcDatatitle":"AHarmbca Reports","abcData":"300"};
delete myObject.abcDatatitle
console.log(JSON.stringify(myObject));

https://jsfiddle.net/pimboden40/eokdwr4c/7/

CodeHacker
  • 2,127
  • 1
  • 22
  • 35
  • OP has a string. You cannot `delete` part of a string. –  Jan 03 '19 at 15:30
  • @sferret you cannot parse an object. JSON.parse converts a string to a Javascript Object : This is a string: '{"prop":"val"}'. This is an object: {"prop":"val"} – CodeHacker Jan 03 '19 at 15:52
1

use JSON.parse then delete the object key, then use JSON.stringify

//convert string to object
var key = localStorage.getItem(localStorage.key(0))
var objKey = JSON.parse(key)
delete objKey.abcDatatitle

//parse to string again
var strKey = objKey = JSON.stringify(objKey)

// update localStorage
localStorage.setItem(localStorage.key(0), strKey)
Cristyan
  • 650
  • 4
  • 15
  • I have performed this step, however, when I print ` var key = localStorage.getItem(localStorage.key(0));`, I would see same thing again : `{"logged_user":"myname","abcDatatitle":"AHarmbca Reports","abcData":"300"};` – John Jan 03 '19 at 15:32
1

you can do this

//the key is localStorage.key(0)
localStorage.setItem(localStorage.key(0),'{"logged_user":"myname","abcDatatitle":"AHarmbca Reports","abcData":"300"}')
// we get the object data using JSON.parse(string)
obj = JSON.parse(localStorage.getItem(localStorage.key(0)));
// we delete the property
delete obj.abcDatatitle
// we store the new object as string using JSON.stringify(json)
localStorage.setItem(localStorage.key(0),JSON.stringify(obj));
Islam ElHakmi
  • 274
  • 2
  • 10