根据数组值获取子数组

时间:2019-04-16 08:45:54

标签: javascript arrays object

我有一个categories数组:

{id: 1, catName: "test", subCategories: Array(2)}

我需要基于subCategories的{​​{1}}来检索id数组。

这将返回整个category对象,如何更改为仅返回category数组?

subCategories

5 个答案:

答案 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是一个非常强大的工具。 findmapforEachfilter类似于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;
        }
    }