Lodash从混合数组和对象中获取叶子

时间:2019-01-11 15:32:13

标签: javascript arrays object lodash

让我先向您展示代码,然后再解释我的需求。我想向您展示输入数组的结构和所需的结果:

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

我需要得到什么?

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

希望您能明白。基本上,我需要以某种方式获取不包含子项subCats的最后一个subCats元素,并将其追加到结果数组中。 我尝试使用Lodash,因为它非常适合数组/对象操作。谢谢您的帮助。

3 个答案:

答案 0 :(得分:1)

编写一种无需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');

答案 1 :(得分:1)

尝试一下

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

答案 2 :(得分:1)

挺直的,不需要lodash。递归函数..

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