我正在尝试使用map来遍历嵌套数组。
const results = [
{
id: 1,
details: [
{
color: "red",
}
]
},
{
id: 2,
details: [
{
color: "blue",
}
]
}]
const list1 = results.map(car => {
return car.details;
})
const list2 = list.map(details => {
return {
detail: details.color
}
});
console.log(list1);
console.log(list2);
List1显示正常:
[ [ { color: 'red' } ], [ { color: 'blue' } ] ]
然而,对于list2,我得到以下内容:
[ { detail: undefined }, { detail: undefined } ]
有人可以帮我映射嵌套数组吗?
答案 0 :(得分:3)
尝试以下
const results = [
{
id: 1,
details: [
{
color: "red",
}
]
},
{
id: 2,
details: [
{
color: "blue",
}
]
}]
const list1 = results.map(car => {
return car.details;
});
// assuming there was a typo here it should be list1
const list2 = list1.map(details => {
return {
detail: details[0].color // details is an array
}
});
console.log(list1);
console.log(list2);

答案 1 :(得分:1)
您需要映射内部数组值并将它们连接到单个数组。
var results = [{ id: 1, details: [{ color: "red" }] }, { id: 2, details: [{ color: "blue" }] }],
list1 = results.map(({ details }) => details);
list2 = list1.reduce(
(r, details) => r.concat(details.map(({ color: detail }) => ({ detail }))),
[]
);
console.log(list2);
console.log(list1);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)
您使用的list
变量名list1
不正确,然后在map
内需要访问每个details
数组的对象list1
}:
const results = [
{
id: 1,
details: [
{
color: "red",
}
]
},
{
id: 2,
details: [
{
color: "blue",
}
]
}]
const list1 = results.map(car => {
return car.details;
})
const list2 = list1.map(details => {
return {
detail: details[0].color
}
});
console.log(list1);
console.log(list2);
答案 3 :(得分:0)
您的代码存在以下问题:
list
中的错字。您想改用list1
。list1
中,details
是一个数组。所以你需要在索引的基础上获得颜色。
const results = [{
id: 1,
details: [{
color: "red",
}]
},
{
id: 2,
details: [{
color: "blue",
}]
}
]
const list1 = results.map(car => car.details);
const list2 = list1.map(details => ({ detail: details[0].color }));
console.log(list1);
console.log(list2);

答案 4 :(得分:0)
You forgot the dynamic index of the array.
const results = [
{
id: 1,
details: [
{
color: "red",
}
]
},
{
id: 2,
details: [
{
color: "blue",
}
]
}]
const list1 = results.map((car, i) => {
return car[i].details;
})
const list2 = list.map((details, i) => {
return {
detail: details[i].color
}
});
console.log(list1);
console.log(list2);
答案 5 :(得分:0)
问题是color
中每个properties
的{{1}} details
都嵌套在list2
中。
要公开他们:说arrays
必须是arrays
。
flattened
的{{1}} Arrays
可以arrays
简洁地使用Array.prototype.concat()
和Function.prototype.apply()
,如下所示:
flattened
请参阅下面的实例。
const flattened = [].concat.apply([], [[1, 2], [3, 4]]) // [1, 2, 3, 4]