预期效果:迭代数组中的对象,在数组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
}
答案 0 :(得分:1)
您还需要迭代comments
并获取属性email
。
使用for ... of
statement和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);
}
}
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