Expected effect: iterate objects in array, get value example 'email' in objects in array comments
.
I would like to spell the array and nested objects and arrays and return the 'email' value. When I get array comments
I try to get value email in object I have error email is undefined
let scores = [
{
"userId": 1,
"id": 1,
"title": "bbbb",
"project": "JS",
"completed": false,
"comments": [
{
"itemId": 1,
"id": 1,
"name": "provident id voluptas",
"email": "[email protected]",
"body": "sdsdsd"
},
{
"itemId": 1,
"id": 2,
"name": "provident id voluptas",
"email": "[email protected]",
"body": "sdsdsd"
}
]
},
{
"userId": 1,
"id": 2,
"title": "ggggg",
"comments": [
{
"itemId": 2,
"id": 1,
"name": "odio adipisci rerum aut animi",
"email": "[email protected]",
"body": "dsdsdsd"
}
]
}
]
let obj;
for (var key in scores) {
obj = scores[key];
console.log(obj.comments); //return objects array
}
for (var key in ob) {
let ob1 = ob[key];
console.log(ob1[email]); //return email is undefined
}
You need to iterate comments
as well and get the property email
.
With for ... of
statement and destructuring assignment.
let scores = [{ userId: 1, id: 1, title: "bbbb", project: "JS", completed: false, comments: [{ itemId: 1, id: 1, name: "provident id voluptas", email: "[email protected]", body: "sdsdsd" }, { itemId: 1, id: 2, name: "provident id voluptas", email: "[email protected]", body: "sdsdsd" }] }, { userId: 1, id: 2, title: "ggggg", comments: [{ itemId: 2, id: 1, name: "odio adipisci rerum aut animi", email: "[email protected]", body: "dsdsdsd" }] }];
for (let { comments } of scores) {
for (let { email } of comments) {
console.log(email);
}
}
With Array#forEach
let scores = [{ userId: 1, id: 1, title: "bbbb", project: "JS", completed: false, comments: [{ itemId: 1, id: 1, name: "provident id voluptas", email: "[email protected]", body: "sdsdsd" }, { itemId: 1, id: 2, name: "provident id voluptas", email: "[email protected]", body: "sdsdsd" }] }, { userId: 1, id: 2, title: "ggggg", comments: [{ itemId: 2, id: 1, name: "odio adipisci rerum aut animi", email: "[email protected]", body: "dsdsdsd" }] }];
scores.forEach(({ comments }) => comments.forEach(({ email }) => console.log(email)));