Home > Software engineering >  Looping through and parsing JSON objects within arrays that are stored in local storage
Looping through and parsing JSON objects within arrays that are stored in local storage

Time:09-30

I'm trying to obtain the email from my users by looping through and parsing stringified arrays containing an object within local storage.

User1632925384043: "[{\"first\":\"James\",\"last\":\"Chen\",\"email\":\"[email protected]\",\"pass\":\"2222222222222222222\"}]"
User1632982295360: "[{\"first\":\"Sarah\",\"last\":\"Jones\",\"email\":\"[email protected]\",\"pass\":\"444444444444444444\"}]"

With the way my data is being stored, I'm having a hard time traversing through the objects and grabbing the data I want.

With a simple array containing an object, I would do something like this to grab the email -

const employees = [
    {
        name: "Harri",
        email: "[email protected]",
        role: "English Teacher"
    }
]

const emails = () => {
    employees.forEach(employee => {
        // console.log(employee.email);
        return employee.email;
    })
}

But in this case, having the objects stored in local storage adds another layer (the local storage object).

Also, trying to JSON.parse() the data returns this error -

Uncaught SyntaxError: Unexpected token s in JSON at position 0 at JSON.parse (<anonymous>)

Say if I remove JSON.parse, with this code -

Object.keys(localStorage).forEach(key => {
    console.log(localStorage.getItem(key));
    const user = localStorage.getItem(key);
    for (const prop in user) {
        console.log(`${prop}: ${user[prop]}`);
    }
 });

I then end up looping through each individual character of the key value pairs e.g. -

11: S
sign-in.js:42 12: a
sign-in.js:42 13: r
sign-in.js:42 14: a
sign-in.js:42 15: h
sign-in.js:42 16: "
sign-in.js:42 17: ,
sign-in.js:42 18: "
sign-in.js:42 19: l
sign-in.js:42 20: a
sign-in.js:42 21: s
sign-in.js:42 22: t
sign-in.js:42 23: "
sign-in.js:42 24: :
sign-in.js:42 25: "
sign-in.js:42 26: J
sign-in.js:42 27: o
sign-in.js:42 28: n
sign-in.js:42 29: e
sign-in.js:42 30: s

As you'd expect, I don't want to loop through every character. I want to loop through the keys in my object so I can obtain the email.

I also don't understand the ```/''' within my objects and whether or not it's affecting my ability to navigate through them.

This data is collected from user inputs -

const saveUser = () => {
    inputs = [signUpForm.querySelectorAll(".signUpInput")].map(input => {
        first = firstName.value;
        last = lastName.value;
        email = signUpEmail.value;
        pass = signUpPass.value;

        return { first, last, email, pass }
    });
        // sets unique user
        localStorage.setItem("User"   new Date().getTime(), JSON.stringify(inputs));
        data.email = email;
        data.pass = pass;
        users.push(data);
        // console.log(users);
        data = {};
};

Can I/should I retrieve the data I want when it's stored in this way? Or do I need to change how it's being stored?

If having the data stored like this is okay, how can I parse it then retrieve it without receiving an error?

CodePudding user response:

Use

you have do only one foreach loop remove for loop inside of foreach

Object.keys(localStorage).forEach(key => {
console.log(localStorage.getItem(key));
const user = localStorage.getItem(key);

    console.log( ${user}`);

});

CodePudding user response:

Check this code, it may help you,

const saveUser = () => {
  let user = {};
  var inputs = [...signUpForm.querySelectorAll(".signUpInput")].forEach(input => {
    user[input.name] = input.value;
  });
  let currentUsers = localStorage.getItem("Users");
  currentUsers = !currentUsers ? currentUsers = [] : JSON.parse(currentUsers);
  currentUsers.push(user); //you can check whether this user exists and can update
  localStorage.setItem("Users", JSON.stringify(currentUsers));
};
const showSavedUsers = () => {
  let currentUsers = JSON.parse(localStorage.getItem("Users"));
  currentUsers.forEach(e => {
    console.log(e.signUpEmail);
  });
}
saveUser();
showSavedUsers();
  • Related