无法弄清楚如何对这种结构进行排序:
[
0: { text: 'Lorem', 'children': [ 0: { text: 'Ipsum of Lorem' } ... ] }
...
]
我只能按第一级排序,如下所示:_.sortBy(myArray,'text')
我需要像 _.sortBy(myArray, ['text','children.text'])
这样的东西,这显然不起作用。
我需要按每个项目的children.text 进行排序。
最佳答案
您应该循环遍历子数组。
const myArray = [{ text: 'ZLorem', 'children': [{ text: 'Ipsum2' }, { text: 'Apsum2' }] },{ text: 'Lorem', 'children': [{ text: 'Ipsum1' }, { text: 'Zpsum1' }] }],
result = _.sortBy(myArray, 'text');
result.forEach(o => {
if (o.children)
o.children = _.sortBy(o.children, 'text');
});
console.log(result);
.as-console-wrapper { min-height: 100%; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
关于javascript - ES6,Lodash sortBy 2 级对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57328627/