每次加载我的应用程序时,我都会收到以下 json
:
[
{
id: 'mALRRY93jASr',
identifier: '100',
text: 'Text A'
},
{
id: '7S3xHZEdNcfV',
identifier: '200',
text: 'Text B'
},
{
id: '2ZA5xSJeukU6',
identifier: '300',
text: 'Text C',
},
{
id: 'bhg3GnLEvw2k',
identifier: '300.100',
text: 'Text C - A'
},
{
id: 'bhg3GnLEvw2k',
identifier: '300.100.100',
text: 'Text C - A - A'
},
{
id: '2AcXNr4HT388',
identifier: '300.200',
text: 'Text C - B'
}
]
树级别由 identifier
属性标识。
树可以有数千个子节点,因此它需要递归。
如何使用 Lodash 排列 json
看起来像下面的 json
?
[
{
id: 'mALRRY93jASr',
identifier: '100',
text: 'Text A'
},
{
id: '7S3xHZEdNcfV',
identifier: '200',
text: 'Text B'
},
{
id: '2ZA5xSJeukU6',
identifier: '300',
text: 'Text C',
children: [
{
id: 'bhg3GnLEvw2k',
identifier: '300.100',
text: 'Text C - A',
children: [
{
id: 'bhg3GnLEvw2k',
identifier: '300.100.100',
text: 'Text C - A - A'
}
]
},
{
id: '2AcXNr4HT388',
identifier: '300.200',
text: 'Text C - B'
}
]
}
]
最佳答案
您可以采用迭代方法,在标识符
的同一路径中查找对象并构建嵌套结构。
此方法也适用于未排序的数据。
var data = [{ id: 'mALRRY93jASr', identifier: '100', text: 'Text A' }, { id: '7S3xHZEdNcfV', identifier: '200', text: 'Text B' }, { id: '2ZA5xSJeukU6', identifier: '300', text: 'Text C' }, { id: 'bhg3GnLEvw2k', identifier: '300.100', text: 'Text C - A' }, { id: 'bhg3GnLEvw2k', identifier: '300.100.100', text: 'Text C - A - A' }, { id: '2AcXNr4HT388', identifier: '300.200', text: 'Text C - B' }],
tree = [];
data.reduce((r, o) => {
o.identifier
.split('.')
.map((_, i, a) => a.slice(0, i + 1).join('.'))
.reduce((q, identifier, i, { length }) => {
var temp = (q.children = q.children || []).find(p => p.identifier === identifier);
if (!temp) {
q.children.push(temp = { identifier });
}
if (i + 1 === length) {
Object.assign(temp, o);
}
return temp;
}, r);
return r;
}, { children: tree });
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - Lodash - 如何从平面数组创建树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53818897/