admin管理员组

文章数量:1355595

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

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;
  });
Share Improve this question edited Apr 16, 2019 at 8:52 Jack Bashford 44.2k11 gold badges55 silver badges82 bronze badges asked Apr 16, 2019 at 8:45 user3378165user3378165 6,92618 gold badges66 silver badges108 bronze badges 1
  • I have a categories array.. That looks like object, not an array – hindmost Commented Apr 16, 2019 at 8:53
Add a ment  | 

5 Answers 5

Reset to default 5

Destructure a find call:

const { subCategories } = categoriesWithSub.find(({ id }) => id === departments.catId);

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

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.

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

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

本文标签: javascriptGet sub array based on array valueStack Overflow