向地图功能添加条件

时间:2019-01-24 17:49:04

标签: javascript

我有这个map功能:

  return docTypes.map(docType => ({
    label: docType.docType,
    value: docType.id,
  }));

如何添加仅在docType.generic = true时才返回的条件?

3 个答案:

答案 0 :(得分:2)

在您的map之前添加一个filter

return docTypes.filter(docType => docType.generic).map(docType => ({
  label: docType.docType,
  value: docType.id,
}));

答案 1 :(得分:2)

您可以结合使用.filter和.map

return docTypes.filter(docType => docType.generic)
  .map(docType => ({
    label: docType.docType,
    value: docType.id,
  }));

答案 2 :(得分:1)

实际上,要在数组上迭代一次,可以使用reduce()

const docTypes = [
    {docType: "csv", id: 10, generic: true},
    {docType: "txt", id: 20, generic: false},
    {docType: "wav", id: 30, generic: true}
];

let res = docTypes.reduce((res, curr) =>
{
    if (curr.generic)
        res.push({label: curr.docType, value: curr.id});

    return res;
}, []);

console.log(res);