js 过滤 json 数据

2 篇文章 0 订阅
1 篇文章 0 订阅


一、一维数组过滤

1、filter

let arr = [
  {id: 1,name: "张三",age: 18},
  {id: 2,name: "李四",}
]
arr = arr.filter(item => !!item.age);
console.log(arr) // [{id: 1,name: "张三",age: 18}]

2、map

let arr = [
  {id: 1,name: "张三",},
  {id: 2,name: "李四",}
]
let ids = arr.map(item => item.id);
console.log(ids) // [1,2]

二、复杂数组过滤

map、filter 结合使用

/**
* sub.id: 123
* row.id: "id-123"
* 输出sub.id和row.id不同的项
*/
let new_arr = old_arr.map((item, index) => {
  if (!!item.children)
    item.children = item.children.filter(sub => sub.id !== row.id)
  return item;
}).filter(item => item.children && item.children.length > 0);

三、树形数据过滤

递归

// 过滤有文件的数据
filterTree(tree) {
  const result = [];
  for (const item of tree) {
    const res = this.heplFun(item);
    if (res) {
      result.push(res);
    }
  }
  return result;
},
// 过滤文件的条件
heplFun(item) {
  // 判断条件地方
  if (item.pageCount) {
    return item;
  }
  const curent = { ...item, children: [] };
  if (item.children && item.children.length > 0) {
    for (const child of item.children) {
      const res2 = this.heplFun(child);
      if (res2) {
        curent.children.push(res2);
      }
    }
  }
  return curent.children.length > 0 ? curent : null;
},

四、过滤附件数组 — filter、map、findIndex

/**
* 给fileList数组的url加api前缀
* previewSrcList 过滤fileList的url组成新数组
* Index 附件预览时图片地址在previewSrcList数组中的下标
*/
fileList.filter(item => {
	return item.url = item.url.indexOf('/Api') > -1 ? item.url : '/Api' + item.url
})
previewSrcList = fileList.map(item => item.url)
Index = previewSrcList.findIndex(item => item === file.url);

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值