使用地图创建对象,也有条件

Use map to create object and also on a condition

我有一个这样的数组 -

details = [{
    id: 1,
    name: 'xyz'
    type: 1
    coun1: 5,
    count2: 6
  },
  {
    id: 2,
    name: 'abc'
    type: 2
    coun1: 4,
    count2: 3
  },
  {
    id: 3,
    name: 'def'
    type: 1
    coun1: 2,
    count2: 8
  }
]

如果我这样做

updatedInfo = details.map(data = > {
  if (type == 1) {
    return {
      totalCount = data.count1 + data.count2
    }
  }
});

我正在获取类型 1 的 totalCount,但对于其他类型它不应该 return 但它 return 未定义。

将“类型”替换为“data.type”

输入和输出数组之间存在 1:1 映射 Array.map

如果 type == 1false,则您的映射函数隐式 returns undefined(实际上应该是 data.type == 1,如其他 answers/comments 中突出显示的) .这些是输出数组中的 undefined 值。

你应该过滤,然后映射:

details.filter((data) => d.type === 1)
       .map((data) => data.count1 + data.count2)

.map() 将对所有元素 运行 并创建一个相同长度的转换数组。您只是 return 为特定条件设置一个元素。对于其他默认值,它将是 undefined。 (不 return 任何东西的函数 return 未定义)

此外,type==1 应该不起作用。你的意思可能是 data.type == 1.

无论如何,如果只得到type == 1的数据,你需要先.filter()取出一些元素,然后用.map()转换成你需要的结果。

updatedInfo = details.filter(data = > {
 return data.type == 1;
}).map(x => {
   return { 'totalCount' : x.count1 + x.count2 }
});

如果您尝试将另一个 属性 (total_count) 添加到那些类型为 ==1 的对象,您可以 filter(),然后 map() 并使用spread {...} 语法添加新的 属性

updatedInfo = details.filter(e => e.type === 1)
          .map(e => ({ ...e, total_count: (e.coun1 + e.count2)}))

details = [{
    id: 1,
    name: 'xyz',
    type: 1,
    coun1: 5,
    count2: 6
  },
  {
    id: 2,
    name: 'abc',
    type: 2,
    coun1: 4,
    count2: 3
  },
  {
    id: 3,
    name: 'def',
    type: 1,
    coun1: 2,
    count2: 8
  }
]

updatedInfo = details.filter(e => e.type === 1).map(e => ({ ...e,
  total_count: (e.coun1 + e.count2)
}))

console.log(updatedInfo)