我有这个map
功能:
return docTypes.map(docType => ({
label: docType.docType,
value: docType.id,
}));
如何添加仅在docType.generic = true
时才返回的条件?
答案 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);