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
[{"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).
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