Search code examples
javascriptnode.jsrhino

Parse array of objects recursively and filter object based on id


i have this array of objects : getCategory (variable)

[
  {
    "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"
          },

and i tried everything i could search in stackoverflow ..

lets say on this array i want to get recursively and object with the specified id .. like 20596 and it should return

{
            "id": "20596",
            "name": "Soin cheveux colorés"
          }

The logic way i am doing is like this :

var getSubcategory = getCategory.filter(function f(obj){
        if ('subCategory' in obj) {
            return obj.id == '20596' || obj.subCategory.filter(f);
        }
        else {
            return obj.id == '20596';
        }
    });

dont know what else to do . Thanks

PS : I dont use it in browser so i cannot use any library . Just serverside with no other library . find dont work so i can only use filter


Solution

  • You need to return the found object.

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