I have a categories
array:
{id: 1, catName: "test", subCategories: Array(2)}
I need to retrieve the subCategories
array based on the id
of the category
.
This return the entire category
object, how can I change it to only return the subCategories
array?
const subCategories = categoriesWithSub.filter(category => {
return category.id === departments.catId;
});
Destructure a find
call:
const { subCategories } = categoriesWithSub.find(({ id }) => id === departments.catId);
You can use reduce
.
const subCategories = categoriesWithSub.reduce((acc, category) => {
if (category.id === departments.catId) {
return acc.concat(category. subCategories)
}
return acc;
}, []);
Side note, reduce
is a really powerful tool. find
, map
, forEach
, filter
are like shorthand versions of reduce
for specific tasks.
Use Array#find
to get the object and get the array using 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
Try this:
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With