1

I am trying to iterate through the values in an object.

Here are the values of the object:

object=Object.values(localStorage)[0];
console.log(object);

Output

{"name":"e7","id":"7","category":"n"}

I tried:

console.log(object[0]);

But it printed just "{"... Then I tried... object[name], object['name'] , object[0][0]... but the output is not satisfactory...

I want to loop through these values like I want to access "name" and its value and so on...

Can I loop through individual values of JavaScript?

the output is actually a value ..

cyber_fish
  • 67
  • 9
  • 7
    You don't actually have an object, but a string. It's serialised JSON. You need to `JSON.parse` it to produce an actual object. Then you can get its values using `Object.values` just like before. – VLAZ Mar 27 '20 at 14:58
  • LocalStorage can only store strings, not objects directly. – Jeremy Thille Mar 27 '20 at 14:59
  • "the output is not satisfactory" is not a satisfactory problem description. – Anders Lindén Mar 27 '20 at 15:00
  • Try typeof to see what is happening – Norhther Mar 27 '20 at 15:00
  • Does this answer your question? [Setting and getting object to local storage using stringify?](https://stackoverflow.com/questions/12051357/setting-and-getting-object-to-local-storage-using-stringify) – VLAZ Mar 27 '20 at 15:00
  • by writing "r=JSON.parse(m[0]) " and then" r.name" i get value of name (key)... how can i get key by mentioning value? – cyber_fish Mar 27 '20 at 15:07

1 Answers1

1

Local storage can only store strings, so what you get from it is just a JSON string and you have to parse it into a JavaScript object before you can use it like one.

The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings).

You can do it by calling JSON.parse() (documentation here).

var fromLocalStorage = '{"name":"e7","id":"7","category":"n"}';

// Parse the JSON string from localStorage into a JS object
var object = JSON.parse(fromLocalStorage);

// Get a single property
console.log(object.name);

// Loop all the key-value pairs of the object
Object.keys(object).forEach(function(key) {
    console.log(key + ' -> ' + object[key]);
});
vicpermir
  • 3,544
  • 3
  • 22
  • 34