概述
let userArr = [
{ organId: "404501528292864000", organCode: "000500020001", indexs: "5", organName: "jc", organEncode: "jc-000-001" },
{ organId: "404501543019065344", organCode: "000500020002", indexs: "8", organName: "jc", organEncode: "jc-000-001" },
{ organId: "404501558844174336", organCode: "000500020003", indexs: "7", organName: "jc", organEncode: "jc-000-001" },
{ organId: "404501558844174336", organCode: "0005000200030001", indexs: "9", organName: "jc", organEncode: "jc-000-001" },
{ organId: "404501558844174666", organCode: "0005", indexs: "9", organName: "jc", organEncode: "jc-000-001" },
{ organId: "404501450253643776", organCode: "00050000", indexs: "2", organName: "jc", organEncode: "jc-000-001" },
{ organId: "404501470239502336", organCode: "00050001", indexs: "4", organName: "jc", organEncode: "jc-000-001" },
{ organId: "404501486886694912", organCode: "00050002", indexs: "3", organName: "jc", organEncode: "jc-000-001" },
{ organId: "404501511574368256", organCode: "000500020000", indexs: "6", organName: "jc", organEncode: "jc-000-001" },
]
let newArr = userArr.filter(
item => item.organCode.length === 4//筛选code里面的长度是4的
);
newArr.forEach(item => {
item.children = filter(item, item.organCode.length)
})
function filter(item, length) {
let arr = userArr.filter(
users =>
item.organCode !== users.organCode &&
item.organCode == users.organCode.substring(0, length) &&
users.organCode.length === length + 4
);
if (arr.length > 0) { //第一种方式 是保留children 就算为空也会有children
arr.forEach(item => {
item.children = filter(item, item.organCode.length)
})
}
if (arr.length > 0) { //第二种方式 只要children就去掉
arr.forEach(item => {
let list = filter(item,item.code.length)
if(list.length > 0) {
item.children = list
}
})
}
return arr
}
newArr.map((item) => { // 配合第二种方式 这是去掉一级的children
if (item.children.length>0) {
return item
} else {
delete item.children
return item
}
})
console.log(newArr)
还有一种情况需求,我想取这个数组最短的code来当做第一级。但是第一级的长度不知道是多少,以至于这个一级长度不能写死
let newArr = userArr.filter(
item => item.organCode.length === ? //这个长度不能写死
);
来,我们解决一下
function compare(property){
return function(a,b){
var value1 = a[property];
var value2 = b[property];
return value1 - value2;
}
}
let hahaha = userArr.sort(compare('organCode'))
let shen =hahaha[0].organCode.length
console.log(shen)
把数组的 某一个参数 进行数组排序。那么最短的一定实在第一个,然后拿到第一个数组对象里的参数就行。起一个变量 把 长度 赋值给 ?的位置即可!
最后
以上就是热情煎饼为你收集整理的js 无限循环嵌套的全部内容,希望文章能够帮你解决js 无限循环嵌套所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复