【问题标题】:Is there a way to reduce a nested json by extracting only certain values? [duplicate]有没有办法通过只提取某些值来减少嵌套的 json? [复制]
【发布时间】:2021-10-20 04:37:26
【问题描述】:

我有以下嵌套的 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"]

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

【问题讨论】:

  • 那不是一个有效的对象。
  • 那不是json,字段名要用双引号括起来"

标签: javascript ecmascript-6


【解决方案1】:

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

【讨论】:

  • 那是什么魔法? :D 你能不能给我推荐一个很好的教程来理解你写的东西?
  • @Phate 你可以从基本的递归和 es6 开始
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-29
  • 1970-01-01
  • 1970-01-01
  • 2021-06-22
相关资源
最近更新 更多