假设这个数组:
[
{ department: "D1", section: "S1", name: "Test", other: "value", hierarchy: 1 },
{ department: "D2", section: "S1", name: "Test", other: "value", hierarchy: 1 },
{ department: "D2", section: "S2", name: "Test", other: "value", hierarchy: 2 }
]我想按部门、部门对数据进行分组,并对部门、部门、层次结构进行排序
结果将是:
[
"D1": [
"S1": [
{ name: "Test", other: "value" }
]
],
"D2": [
"S1" [
{ name: "Test", other: "value" }
],
"S2" [
{ name: "Test", other: "value" },
{ name: "Test", other: "value" }
]
]
]这是我前进方向的一个框架:
var grouped = _.mapValues(_.chain(data).sortBy(item => item.hierarchy).groupBy(item => item.department).value(),
clist => clist.map(data => _.omit(data, 'department')));
_.forEach(grouped, function (item, department) {
const members = _.groupBy(item, (item) => {
return [item['section'], item['name']];
});
});有没有更好的方法使用Lodash来实现它?
发布于 2021-07-15 23:03:42
我建议先使用_.groupBy,然后使用_.mapValues。
groupBy调用将按部门分组,然后我们再次使用groupBy使用mapValues将每个部门按部门分组。
const arr = [
{ department: "D1", section: "S1", name: "Test", other: "value", hierarchy: 1 },
{ department: "D2", section: "S2", name: "Test", other: "value", hierarchy: 2 },
{ department: "D2", section: "S1", name: "Test", other: "value", hierarchy: 1 },
{ department: "D2", section: "S2", name: "Test", other: "value", hierarchy: 2 }
]
const result = _.mapValues(_.groupBy(arr, 'department'), (v,k) => _.groupBy(v, 'section'));
console.log('Result:', result);<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>
发布于 2021-07-15 23:05:20
您可以使用vanilla javascript中的sort()和reduce()实现这一点。
const
input = [
{ department: "D2", section: "S1", name: "Test-d2-s1-h1", other: "value", hierarchy: 1 },
{ department: "D2", section: "S2", name: "Test-d2-s2-h2", other: "value", hierarchy: 2 },
{ department: "D1", section: "S1", name: "Test-d1-s1-h1", other: "value", hierarchy: 1 },
{ department: "D2", section: "S2", name: "Test-d2-s2-h1", other: "value", hierarchy: 1 },
],
result = input
.sort((a, b) =>
a.department.localeCompare(b.department)
|| a.section.localeCompare(b.section)
|| a.hierarchy - b.hierarchy)
.reduce((a, { department, section, hierarchy, ...data }) => (
((a[department] ??= {})[section] ??= []).push(data), a
), {});
console.log(result).as-console-wrapper { max-height: 100% !important; top: 0; }
https://stackoverflow.com/questions/68396148
复制相似问题