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
5 Answers
Reset to default 5Destructure 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
版权声明:本文标题:javascript - Get sub array based on array value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743977396a2570932.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论