Reputation: 1
Actually I am trying to retrieve all the values of email field from array containing objects. But I couldn't able to do it. Please help me out.
function User(name,email,pswd,repswd)
{
this.name=name;
this.email=email;
this.pswd=pswd;
this.repswd=repswd;
}
add();
function add(){
let myUserObj=new User(document.getElementById('name').value,document.getElementById('email').value,document.getElementById('pswd').value,document.getElementById('repswd').value);
localStorage.setItem(document.getElementById("name").value,JSON.stringify(myUserObj));
let myObj=JSON.parse(localStorage.getItem(document.getElementById("name").value));
var arr=new Array();
for(var i=0;i<localStorage.length;i++){
// console.log("User"+(i+1)+" "+localStorage.getItem(localStorage.key(i)));
arr[i]=localStorage.getItem(localStorage.key(i));
}
console.log(arr);
for(var i=0;i<arr.length;i++)
{
for(var j=0;j<arr[i].length;j++)
{
console.log(arr[i]+"\n");
}
}
Firstly I took inputs from user and accessed it with constructor then I stored in local storage from it Stored to array. So what exactly i'm trying to do is to get all the values of email field from that array but i couldn't able to get it.
The output which i'm getting is below
(2) ["{"name":"xyz","email":"[email protected]","pswd":"Xyz@1234","repswd":"Xyz@1234"}", "{"name":"ritu","email":"[email protected]","pswd":"Ritu1234","repswd":"Ritu1234"}"]
76 {"name":"xyz","email":"[email protected]","pswd":"Xyz@1234","repswd":"Xyz@1234"}
75 {"name":"ritu","email":"[email protected]","pswd":"Ritu1234","repswd":"Ritu1234"}
please help me out to retrieve the email values.
Upvotes: 0
Views: 990
Reputation: 7852
You should be able to get the emails just by using map
:
function User(name, email, pswd, repswd) {
this.name = name;
this.email = email;
this.pswd = pswd;
this.repswd = repswd;
}
const arr = [
new User('user1', '[email protected]', 'secret1', 'secret1'),
new User('user2', '[email protected]', 'secret2', 'secret2'),
new User('user3', '[email protected]', 'secret3', 'secret3'),
];
const emails = arr.map(user => user.email);
console.log(emails);
Upvotes: 1