如果数组在对象中,而对象在下一个数组中,则如何在数组的对象中获取值?

时间:2019-06-12 07:37:14

标签: javascript arrays object ecmascript-6 javascript-objects

预期效果:迭代数组中的对象,在数组comments中的对象中获取值示例“ email”。 我想拼写该数组以及嵌套的对象和数组并返回'email'值。当我得到数组comments时,我试图在对象中收到有价值的电子邮件,错误为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 个答案:

答案 0 :(得分:1)

您还需要迭代comments并获取属性email

使用for ... of statementdestructuring 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);
    }
}

使用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)));

答案 1 :(得分:0)

所有电子邮件都需要嵌套循环,但是如果您知道要查找的电子邮件索引,则只需将该索引传递给comments[index]

scores[current_iteration].comments[current_iteration].email