首页 > 解决方案 > 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)

在此处输入图像描述

标签: javascriptarraysdictionary

解决方案


您需要注意从嵌套映射中返回结果,如下所示:

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));

推荐阅读