首页 > 解决方案 > 有没有办法通过只提取某些值来减少嵌套的 json?

问题描述

我有以下嵌套的 json 结构:

{
  element: "a",
  items: ["l1", "l2"],
  children: [{
    element: "b",
    children: [{
      element: "c",
      items: ["l3"]
    }, {
      element: "b",
      child: {
        element: "c",
        items: ["l4"]

      }
    }

基本上:

我想处理这个 json 以获得一个包含所有项目的平面数组:

const finalArray = parse(json); //returns ["l1","l2","l3","l4"]

有没有什么优雅的方法可以通过映射/过滤功能来实现这一点?

标签: javascriptecmascript-6

解决方案


const getItems = (acc = [], { items = [], child = {}, children = [] }) => 
  [
    ...acc, 
    ...items, 
    ...(child?.items || []),
    ...(children.length ? children.reduce(getItems, acc) : [])
  ];

const data = { 
  element:"a",
  items: ["l1","l2"],
  children: [ 
    {
      element: "b",
      children: [
        { element: "c", items: ["l3"] },
        { element: "b", child: { element: "c", items: ["l4"] } }
      ]
    }
  ]
}
console.log( getItems([], data) );


推荐阅读