javascript - Javascript地图问题返回一个空值的数组
问题描述
我正在尝试使用 .map 创建一个名为的新数组,该数组仅在数组中包含 id 但是下面的代码虽然 console.log() 工作正常,并在我使用它workspaces
时按预期在 console.log 中显示 idreturn
不在工作区数组中显示这些 id
const workspaces = this.networkTree.map( (group) => {
group.units.map( (unit) => {
console.log(unit.id); // outputs an id to the console e.g '12345'
return unit.id;
});
});
console.log(workspaces); // each array is empty (see image below)
解决方案
您需要注意从嵌套映射中返回结果,如下所示:
const workspaces = this.networkTree.map( (group) => {
return group.units.map( (unit) => { // <= the `return` here
console.log(unit.id);
return unit.id;
});
});
console.log(workspaces);
如果您不向内联函数添加大括号,另一种方法是:
const workspaces = this.networkTree.map( (group) =>
group.units.map( (unit) => {
console.log(unit.id);
return unit.id;
})
);
当您决定删除console.log
:
const workspaces = this.networkTree.map( (group) => group.units.map( (unit) => unit.id));
推荐阅读
- java - 将文本文件中的特定数据行导入不同的数组
- java - 升级到 1.43 版本后无法运行 JMockit 测试
- bash - 轻松检查 Bash 语句的布尔值
- c# - Send stringified json to serilog as structured data
- r - Keep rows that has specific endings
- r - 使用不添加信息的列扩展数据框
- javascript - JQUERY Forward paging in REST API with deferred
- sql - 结果连接来自公共 ID 的多个列
- python - Take API data from XML and do another API call using Python3
- c# - Using dynamic in .NET Standard library