Search code examples
javascriptarraysobjectlodash

Lodash get leafs from the mixed arrays and objects


Let me first show you the code and then I'll explain my needs. I want to show you the structure of the input array and the desired result:

[
  {
    link: "someurl",
    name: "Foo",
    subCats: [
      {
        link: "anotherurl",
        name: "Bar",
        subCats: [
          {
            link: "anotherurl",
            subCats: [
              {
                link: "onemorekink"
                name: "Prod",
              }
            ]
          }
        ]
      },
      {
        link: "someurll",
        name: "Fuzzy",
        subCats: [
          {
            link: "besturiever",
            name: "SomeName",
            subCats: [
              {
                link: "onemore",
                name: "Aloc",
                subCats: [
                  {
                    link: "anotherlink"
                    name: "Final",
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  }
]

And what do I need to get in the result:

{
  link: "onemorekink"
  name: "Prod",
},
{
  link: "anotherlink"
  name: "Final",
}

I hope you get the idea. Basically I need to somehow get the last subCats element that does not include child subCats and append to the resulting array. I tried using Lodash cause it is perfect for array/object operations. Thanks for help in advance.


Solution

  • Try this

    let b=[]; // result here
    let f = x => x.map( y=> y.subCats ? f(y.subCats) : b.push(y) );
    f(a);
    

    let a = [
      {
        link: "someurl",
        name: "Foo",
        subCats: [
          {
            link: "anotherurl",
            name: "Bar",
            subCats: [
              {
                link: "anotherurl",
                subCats: [
                  {
                    link: "onemorekink",
                    name: "Prod",
                  }
                ]
              }
            ]
          },
          {
            link: "someurll",
            name: "Fuzzy",
            subCats: [
              {
                link: "besturiever",
                name: "SomeName",
                subCats: [
                  {
                    link: "onemore",
                    name: "Aloc",
                    subCats: [
                      {
                        link: "anotherlink",
                        name: "Final",
                      }
                    ]
                  }
                ]
              }
            ]
          }
        ]
      }
    ];
    
    let b=[];
    let f = x => x.map( y=> y.subCats ? f(y.subCats) : b.push(y) );
    f(a);
    
    console.log(b);