Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get sub array based on array value

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;
  });
like image 849
user3378165 Avatar asked Apr 16 '19 08:04

user3378165


4 Answers

Destructure a find call:

const { subCategories } = categoriesWithSub.find(({ id }) => id === departments.catId);
like image 127
Jack Bashford Avatar answered Oct 26 '22 11:10

Jack Bashford


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.

like image 2
hackape Avatar answered Oct 26 '22 11:10

hackape


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
like image 2
Pranav C Balan Avatar answered Oct 26 '22 11:10

Pranav C Balan


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 );
like image 2
Reza Avatar answered Oct 26 '22 10:10

Reza