简体   繁体   中英

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.

It's pretty straight forward to write a method that will do that for you without the need for lodash

function findLastLeafs(items, key) {
  let results = [];
  items.forEach((item, index) => {
    if (item[key] && item[key].length) {
      results = results.concat(findLastLeafs(item[key], key));
    } else if (index === items.length - 1) {
      results.push(item);
    }
  })
  return results;
}

const result = findLastLeafs(data, 'subCats');

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

pretty straight, no lodash is needed. recursive function..

function process(data){
        for(let a of data){
            if(a.subCats){
                process(a.subCats);
            }else{
                console.log(a)
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM