0

In Vue.js: How do I convert an array to an object? I wanted to get name value only "Willy" from the array.

Array data from LocalStorage: [{"id":"56b5","name":"Willy","email":"willy@test","password":"1234"}]

I wanted it to be converted like this : {"id":"56b5","name":"Willy","email":"willy@test","password":"1234"}

Please help.

to further use :

let user = localStorage.getItem('user-info');
this.name = JSON.parse(user).name;

and the result should be "Willy".

4
  • 1
    Don't save an array. Just save the object. Commented Feb 26, 2024 at 7:26
  • I use db.json to store the data and It always return an array from the browser. Commented Feb 26, 2024 at 7:32
  • I think there is a lack of basic understanding of JavaScript Arrays here. If that's the case, check out geeksforgeeks.org/javascript-arrays. Also, have you searched StackOverflow?
    – Stretsh
    Commented Feb 26, 2024 at 7:45
  • What is db.json? There could be a way to not end up with an array in localstorage if you need an object Commented Feb 26, 2024 at 9:14

2 Answers 2

0

[{"id":"56b5","name":"Willy","email":"willy@test","password":"1234"}] is a single object inside an array. You can access it by getting the first object:

let user = localStorage.getItem('user-info');
this.name = JSON.parse(user)[0].name;

You may want to use optional chaining or similar pattern, if no data is in your storage:

let user = localStorage.getItem('user-info');
this.name = JSON.parse(user)?.[0]?.name;
// or
this.name = (JSON.parse(user) ?? [])[0]?.name;

You can also consider saving your user-info as the object instead of as an array (get the first object in the array before saving to local storage).

0

localStorage can only store data in string type. so when saving objects to localStorage, you must convert them to string type, like this one localStorage.setItem('user-info', JSON.stringify({})).

you should convert the value to object type when you get user-info`s data.

const userInfo = JSON.parse('user-info') 

your data is in an array with only one object. so you can directly access this object like this:

const userInfo = JSON.parse('user-info') 
this.name = userInfo[0].name

or

const userInfo = JSON.parse(localStorage.getItem('user-info'))[0]
this.name = userInfo.name

if you want to assign a value only when there is a value. you can do there

const userInfo = JSON.parse('user-info') 
this.name = userInfo[0]?.name

or

const userInfo = JSON.parse(localStorage.getItem('user-info'))[0]
this.name = userInfo?.name

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.