Lodash 按键中的特定 words/prefix 分组
Lodash group by specific words/prefix in a key
我想知道如何使用 Lodash 根据 name
键中的前缀文本(在 : 冒号处拆分名称键)对这个数组进行分组。
const tags = [
{ name: 'Animals: Frogs', id: 1 },
{ name: 'Animals: Lions', id: 2 },
{ name: 'Birds: Crows', id: 3 }
];
to
const tags = [{
animals: [
{ name: 'Frogs', id: 1 },
{ name: 'Lions', id: 2 },
],
birds: [
{ name: 'Crows', id: 3}
]
}];
Lodash 是否有任何功能来处理这个问题,或者是否需要自定义 function/regex?
如果纯JS够用,也可以这样做(结果这里是一个对象,不是数组,但如果需要可以改):
const tags = [
{ name: 'Animals: Frogs', id: 1 },
{ name: 'Animals: Lions', id: 2 },
{ name: 'Birds: Crows', id: 3 }
];
const tags2 = tags.reduce(
(acc, { name, id }) => {
let [group, type] = name.split(': ');
group = group.toLowerCase();
acc[group] ??= [];
acc[group].push({ name: type, id });
return acc;
},
{},
);
console.log(tags2);
我想知道如何使用 Lodash 根据 name
键中的前缀文本(在 : 冒号处拆分名称键)对这个数组进行分组。
const tags = [
{ name: 'Animals: Frogs', id: 1 },
{ name: 'Animals: Lions', id: 2 },
{ name: 'Birds: Crows', id: 3 }
];
to
const tags = [{
animals: [
{ name: 'Frogs', id: 1 },
{ name: 'Lions', id: 2 },
],
birds: [
{ name: 'Crows', id: 3}
]
}];
Lodash 是否有任何功能来处理这个问题,或者是否需要自定义 function/regex?
如果纯JS够用,也可以这样做(结果这里是一个对象,不是数组,但如果需要可以改):
const tags = [
{ name: 'Animals: Frogs', id: 1 },
{ name: 'Animals: Lions', id: 2 },
{ name: 'Birds: Crows', id: 3 }
];
const tags2 = tags.reduce(
(acc, { name, id }) => {
let [group, type] = name.split(': ');
group = group.toLowerCase();
acc[group] ??= [];
acc[group].push({ name: type, id });
return acc;
},
{},
);
console.log(tags2);