我有这个对象数组: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

最佳答案

您需要返回找到的对象。



function find(array, id) {
    var result;
    array.some(function (object) {
        if (object.id === id) {
            return result = object;
        }
        if (object.subCategory) {
            return result = find(object.subCategory, id);
        }
    });
    return result;
}

var data = [{ 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" }] }] }];

console.log(find(data, '20596'));
console.log(find(data, ''));

09-25 18:32
查看更多