javascript - json filter ,json怎么用js过滤

查看:453
本文介绍了javascript - json filter ,json怎么用js过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

  1. 过滤type为1的数据,按原来的层次排列
  2. 原数据

{
    name: '全部文件',
    children: [
        {name: 'hello',
         type: 0,
         children: []
        },
        {name: 'wat',
          type: 1
        },
        {
            name: 'child1',
            type: 0,
            children: [
                {
                    name: 'child11',
                    type: 0,
                    children: [
                        {name: 'hello',
                        type: 1,
                        },
                        {name: 'wat',
                        type: 1,
                        }
                    ]
                },
                {
                    name: 'child12',
                    type: 0,
                    children: [
                        {name: 'hello'
                        type: 0,
                        childen: []
                        },
                        {name: 'wat'
                        type: 1,
                        }
                    ]
                }
            ]
        }
    ]
}

  1. 我想把type为0的全过滤出来按原来的数据排列

解决方案

首先,JSON格式都不对,下次注意咯。

<script async src="//jsfiddle.net/wesleyChen/0j0Lbk3s/embed/js,html,css,result/dark/"></script>

上面是IDE测试,主要的JavaScript:


function getDataByType(type, data) {
  if (!data || data.type !== type) {
    return null;
  }

  if (data.type === type) {
    if (!Array.isArray(data.children)) {
      return data;
    } else {
      const children = data.children
        .map(ele => {
          return getDataByType(type, ele);
        })
        .filter(ele => ele !== null);

      return {
        type: data.type,
        name: data.name,
        children
      };
    }
  } else {
    return null;
  }
}

const result = getDataByType(0, jsonData);

这篇关于javascript - json filter ,json怎么用js过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆