我有下面的代码,我期望从嵌套数组映射结果并返回一个具有两个id的单个数组,但我得到2个数组。有人可以指导我做错了什么吗?
arrayVal = [{
sources: {
data: [{
id: 1
}]
}
},
{
sources: {
data: [{
id: 2
}]
}
}
]
for (let sub of arrayVal) {
let result = sub.sources.data.map(x => (x.id))
console.log(result)
}
答案 0 :(得分:4)
现在,您正在为map
中的每个元素调用arrayVal
,因此您将获得两个数组。请改用reduce
,将一个对象数组转换为另一个数组,该数组与输入元素不一定是:
const arrayVal=[{sources:{data:[{id:1}]}},{sources:{data:[{id:2}]}}];
const result = arrayVal.reduce((a, { sources: { data } }) => (
[...a, ...data.map(({ id }) => id)]
), []);
console.log(result)

答案 1 :(得分:3)
arrayVal = [{
sources: {
data: [{
id: 1
}]
}
},
{
sources: {
data: [{
id: 2
}]
}
}
]
let result = [];
for (let sub of arrayVal) {
result = result.concat(sub.sources.data.map(x => (x.id)))
}
console.log(result)

我认为concat
就是你在这里所缺少的,希望这是你想要实现的目标
答案 2 :(得分:3)
尝试以下
var arrayVal = [{sources: {data: [{id: 1}]}},{sources: {data: [{id: 2}]}}];
// Create an array on sources.data and merge it into 1 collection (array)
var result = arrayVal.reduce((a, c) => [...a, ...c.sources.data.map(({id}) => id)], []);
console.log(result);

供参考,Array.reduce
此外,您可以按如下方式改进代码
var arrayVal = [{sources: {data: [{id: 1}]}},{sources: {data: [{id: 2}]}}];
let result = [];
for (let sub of arrayVal) {
result.push(sub.sources.data.map(x => (x.id)));
}
console.log([].concat(...result))

答案 3 :(得分:1)
试试这个
`Route::middleware(['auth', 'moderator|admin'])->group(function() {
Route::get('/dashboard', function() {
return view('dashboard');
});
});`

答案 4 :(得分:1)
您可以这样做:
arrayVal = [{
sources: {
data: [{
id: 1
}]
}
},
{
sources: {
data: [{
id: 2
}]
}
}
]
var flat = arrayVal.reduce(function(prev,curr,cI){
prev.push(curr.sources.data.map(x => (x.id))[0]);
return prev; // ********* Important ******
}, []);