【发布时间】:2017-07-20 12:08:31
【问题描述】:
我有这个对象数组:getCategory(变量)
[
{
"id": "20584",
"name": "Produits de coiffure",
"subCategory": [
{
"id": "20590",
"name": "Coloration cheveux",
"subCategory": [
{
"id": "20591",
"name": "Avec ammoniaque"
},
{
"id": "20595",
"name": "Sans ammoniaque"
},
{
"id": "20596",
"name": "Soin cheveux colorés"
},
{
"id": "20597",
"name": "Protection"
},
{
"id": "20598",
"name": "Nuancier de couleurs"
}
]
},
{
"id": "20593",
"name": "Soins cheveux",
"subCategory": [
{
"id": "20594",
"name": "Shampooing"
},
{
"id": "20599",
"name": "Après-shampooing"
},
{
"id": "20600",
"name": "Masques"
},
我尝试了我可以在 stackoverflow 中搜索的所有内容..
让我们说在这个数组上我想递归地获取具有指定 id 的对象 .. 像 20596 它应该返回
{
"id": "20596",
"name": "Soin cheveux colorés"
}
我做的逻辑是这样的:
var getSubcategory = getCategory.filter(function f(obj){
if ('subCategory' in obj) {
return obj.id == '20596' || obj.subCategory.filter(f);
}
else {
return obj.id == '20596';
}
});
不知道还能做什么。 谢谢
PS:我不在浏览器中使用它,所以我不能使用任何库。只是服务器端,没有其他库。 find 不工作所以我只能使用filter
【问题讨论】:
标签: javascript node.js rhino