Home > Software design >  how to access the key in json object in react
how to access the key in json object in react

Time:08-04

I am getting the object below its in json form. i wanted to access only user key from the below object. I tried destructuring the object but didnt got expected value;

  const logg=window.localStorage.getItem("userInfo");
 const {user}=logg;
 console.log(user);
console.log(logg.user);
console.log(logg);

enter image description here

{"success":true,"user":{"avatar":{"public_id":"avatars/laqmzy3nuqa5vl7awprh","url":"https://res.cloudinary.com/randomID/image/upload/v1659523730/avatars/laqmzy3nuqa5vl7awprh.jpg"},"_id":"62ea5294ff799046c8173fef","name":"sumit khatri","email":"[email protected]","password":"$2a$10$nSK2JqUSCdVGIVVBzo1IDerU3jrNFfHRDBESV0Ql6y.vWohZiugEG","role":"admin","createdAt":"2022-08-03T10:48:52.355Z","__v":0},"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYyZWE1Mjk0ZmY3OTkwNDZjODE3M2ZlZiIsImlhdCI6MTY1OTUyNzM1NCwiZXhwIjoxNjU5OTU5MzU0fQ.TLJYRAm83qQuLVhVkIqYK0u7WetCm9Hn376VvEPX1Ig"}

CodePudding user response:

The item is in string format try JSON parsing it const {user}=JSON.parse(yourString)

CodePudding user response:

For the data you actually posted at the bottom of your Q, it would be a simple dereference:

const logg = {"success":true,"user":{"avatar":{"public_id":"avatars/laqmzy3nuqa5vl7awprh","url":"https://res.cloudinary.com/randomID/image/upload/v1659523730/avatars/laqmzy3nuqa5vl7awprh.jpg"},"_id":"62ea5294ff799046c8173fef","name":"sumit khatri","email":"[email protected]","password":"$2a$10$nSK2JqUSCdVGIVVBzo1IDerU3jrNFfHRDBESV0Ql6y.vWohZiugEG","role":"admin","createdAt":"2022-08-03T10:48:52.355Z","__v":0},"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYyZWE1Mjk0ZmY3OTkwNDZjODE3M2ZlZiIsImlhdCI6MTY1OTUyNzM1NCwiZXhwIjoxNjU5OTU5MzU0fQ.TLJYRAm83qQuLVhVkIqYK0u7WetCm9Hn376VvEPX1Ig"};
const user = logg.user;
console.log(user);

But if it's still in string form like Alaa said, then you need to do:

const logg = '{"success":true,"user":{"avatar":{"public_id":"avatars/laqmzy3nuqa5vl7awprh","url":"https://res.cloudinary.com/randomID/image/upload/v1659523730/avatars/laqmzy3nuqa5vl7awprh.jpg"},"_id":"62ea5294ff799046c8173fef","name":"sumit khatri","email":"[email protected]","password":"$2a$10$nSK2JqUSCdVGIVVBzo1IDerU3jrNFfHRDBESV0Ql6y.vWohZiugEG","role":"admin","createdAt":"2022-08-03T10:48:52.355Z","__v":0},"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYyZWE1Mjk0ZmY3OTkwNDZjODE3M2ZlZiIsImlhdCI6MTY1OTUyNzM1NCwiZXhwIjoxNjU5OTU5MzU0fQ.TLJYRAm83qQuLVhVkIqYK0u7WetCm9Hn376VvEPX1Ig"}';
const user = JSON.parse(logg).user;
console.log(user);

  • Related