JavaScript 如何从一个数组内的数组中获取值
问题描述
在下面的示例中,为什么我没有得到任何值?
const people = [{
name: "mike",
jobs: ["waiter", "doctor"]
},
{
name: "nils",
jobs: ["singer", "actor"]
},
{
name: "nils",
jobs: ["nurse", "actor"]
},
]
const iterate = people.map(person => {
return person.jobs.map(job => {
return job;
})
return res;
})
console.log(iterate)
const people = [{
name: "mike",
jobs: ["waiter", "doctor"]
},
{
name: "nils",
jobs: ["singer", "actor"]
},
{
name: "nils",
jobs: ["nurse", "actor"]
},
]
let res = []
const iterate = people.map(person => {
return person.jobs.map(job => {
res.push(job)
})
return res;
})
console.log(iterate)
解决方案
该代码将数据从包含对象的数组重新格式化为包含特定人员工作的新数组的数组。
const people = [
{
name: "mike",
jobs: ["waiter", "doctor"]
},
{
name: "nils",
jobs: ["singer", "actor"]
},
{
name: "nils",
jobs: ["nurse", "actor"]
}
];
const iterate = [].concat(...people.map(person => person.jobs));
console.log(iterate);