How get value in the object in the array, if array is in the object and the object in the next array?

Viewed 61

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": "Meghan_Littel@rene.us",
        "body": "sdsdsd"
      },
      {
        "itemId": 1,
        "id": 2,
        "name": "provident id voluptas",
        "email": "fdfdfdf_Littel@rene.us",
        "body": "sdsdsd"
      }
    ]
  },
 {
    "userId": 1,
    "id": 2,
    "title": "ggggg",
    "comments": [
      {
        "itemId": 2,
        "id": 1,
        "name": "odio adipisci rerum aut animi",
        "email": "Nikita@garfield.biz",
        "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
    }
2 Answers

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: "Meghan_Littel@rene.us", body: "sdsdsd" }, { itemId: 1, id: 2, name: "provident id voluptas", email: "fdfdfdf_Littel@rene.us", body: "sdsdsd" }] }, { userId: 1, id: 2, title: "ggggg", comments: [{ itemId: 2, id: 1, name: "odio adipisci rerum aut animi", email: "Nikita@garfield.biz", 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: "Meghan_Littel@rene.us", body: "sdsdsd" }, { itemId: 1, id: 2, name: "provident id voluptas", email: "fdfdfdf_Littel@rene.us", body: "sdsdsd" }] }, { userId: 1, id: 2, title: "ggggg", comments: [{ itemId: 2, id: 1, name: "odio adipisci rerum aut animi", email: "Nikita@garfield.biz", body: "dsdsdsd" }] }];

scores.forEach(({ comments }) => comments.forEach(({ email }) => console.log(email)));

You would need a nested loop for all emails, but if you know the index of the email you are looking for then just pass that index to the comments[index]

scores[current_iteration].comments[current_iteration].email
Related