js 数组对象根据条件转换成多维数组
原数组
const NAVS = [
{
label: 'a',
path: 'a',
children: [],
code: 'HOME',
levelCode: '00'
},
{
label: 'b',
path: '',
code: 'QYBZK',
levelCode: '01',
children: [
{
label: 'b1',
code: 'QYBZKM',
parentCode: 'QYBZK',
levelCode: '0101',
children: [
{
label: 'b11',
code: 'ZYCBKM',
parentCode: 'QYBZKM',
levelCode: '010101',
children: []
}
]
}
]
},
{
label: 'c',
path: '',
code: 'XMGL',
levelCode: '02',
children: [
{
label: 'c1',
code: 'XMGK',
parentCode: 'XMGL',
levelCode: '0201',
children: []
},
{
label: 'c2',
code: 'XMPZ',
parentCode: 'XMGL',
levelCode: '0202',
children: []
}
]
},
{
label: 'd',
code: 'CBDSJ',
levelCode: '03',
children: [
{
label: 'd1',
code: 'CBZB',
parentCode: 'CBDSJ',
levelCode: '0301',
children: [
{
label: 'd11',
code: 'CBZBCX',
parentCode: 'CBZB',
levelCode: '030101',
children: []
},
{
label: 'd12',
code: 'CBZBMXCX',
parentCode: 'CBZB',
levelCode: '030102',
children: []
}
]
},
{
label: 'd2',
code: 'ZBRK',
parentCode: 'CBDSJ',
levelCode: '0302',
children: []
}
]
}
];
筛选条件:
const obj = {
ZBRK: true,
CBZBMXCX: true,
XMPZ: true,
ZYCBKM: true,
HOME: true
}
想得到的数组:
const NAVS = [
{
label: 'a',
path: 'a',
children: [],
code: 'HOME',
levelCode: '00'
},
{
label: 'b',
path: '',
code: 'QYBZK',
levelCode: '01',
children: [
{
label: 'b1',
code: 'QYBZKM',
parentCode: 'QYBZK',
levelCode: '0101',
children: [
{
label: 'b11',
code: 'ZYCBKM',
parentCode: 'QYBZKM',
levelCode: '010101',
children: []
}
]
}
]
},
{
label: 'c',
path: '',
code: 'XMGL',
levelCode: '02',
children: [
{
label: 'c2',
code: 'XMPZ',
parentCode: 'XMGL',
levelCode: '0202',
children: []
}
]
},
{
label: 'd',
code: 'CBDSJ',
levelCode: '03',
children: [
{
label: 'd1',
code: 'CBZB',
parentCode: 'CBDSJ',
levelCode: '0301',
children: [
{
label: 'd12',
code: 'CBZBMXCX',
parentCode: 'CBZB',
levelCode: '030102',
children: []
}
]
},
{
label: 'd2',
code: 'ZBRK',
parentCode: 'CBDSJ',
levelCode: '0302',
children: []
}
]
}
];
根据筛选条件的code值 去找数组中对应的曾经关系,过滤掉没有的。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
...前面刚回答过一个惊人相似的问题。写了个通用函数,直接用吧:
调用: