我有一个categories
数组:
{id: 1, catName: "test", subCategories: Array(2)}
我需要基于subCategories
的{{1}}来检索id
数组。
这将返回整个category
对象,如何更改为仅返回category
数组?
subCategories
答案 0 :(得分:5)
分解一个find
调用:
const { subCategories } = categoriesWithSub.find(({ id }) => id === departments.catId);
答案 1 :(得分:2)
尝试一下:
let categories = [ {id: 1, catName: "test", subCategories: ["test1","test2"]}, {id: 2, catName: "test", subCategories: Array(2)} ]
let departments = { catId: 1 }
const subCategories = categories.find(category => {
return category.id === departments.catId;
}).subCategories;
console.log( subCategories );
答案 2 :(得分:2)
使用Array#find
获取对象,并使用dot notation or bracket notation获取数组。
const subCategories = (categoriesWithSub.find(category => {
return category.id === departments.catId;
}) || {}).subCategories; // if find returns undefined then use an empty object to avoid error, alternately you can use if condition
答案 3 :(得分:2)
您可以使用reduce
。
const subCategories = categoriesWithSub.reduce((acc, category) => {
if (category.id === departments.catId) {
return acc.concat(category. subCategories)
}
return acc;
}, []);
旁注,reduce
是一个非常强大的工具。 find
,map
,forEach
,filter
类似于reduce
的速写版本,用于特定任务。
答案 4 :(得分:0)
尝试
function getSubCategory() {
var categoriesWithSub = [{ id: 1, catName: "test", subCategories: ["test1","test2"] }, { id: 2, catName: "test", subCategories: ["test1","test2"] }]
var catId = 1;
for (var category = 0; category < categoriesWithSub.length; category++) {
if (categoriesWithSub[category].id == catId)
return categoriesWithSub[category].subCategories;
}
}