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

标签 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,因为它非常适合数组/对象操作。提前感谢您的帮助。

最佳答案

试试这个

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

关于javascript - Lodash 从混合数组和对象中获取叶子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54149523/

相关文章:

object - 如何将数据对象内的影片剪辑添加到舞台上? AS3

javascript - Web Audio Api 问题(DOM 异常 12)

javascript - 使用javascript中的reduce方法从数组中删除冗余方向

c - 段错误 : 11 on c program

javascript - 使用 forEach 访问对象数据,而不使用 forEach 的 thisArg?

c++ - 如何使用 json11 库修改 json 对象?

javascript - 如何处理在 vueJS 2 中使用 $emit 传递的参数?

javascript - 使用 bootstrap 和 javascript 在文本框区域 onfocus 事件中添加图标

c - 使用指定的初始化程序初始化数组时出现奇怪的值

c - 使用 C 将字符串的 csv 文件读取到 2D char* 数组