5

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;
  });
1
  • I have a categories array.. That looks like object, not an array Commented Apr 16, 2019 at 8:53

5 Answers 5

5

Destructure a find call:

const { subCategories } = categoriesWithSub.find(({ id }) => id === departments.catId);
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2

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.

Comments

2

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 );

1 Comment

filter will return an array, subCategories will therefor be undefined. [0].subCategories; Would do the trick, but you'd need to be sure that filter always yields results.
0

Try this

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;
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.