【问题标题】:Lodash group by specific words/prefix in a keyLodash 按键中的特定单词/前缀分组
【发布时间】:2021-06-19 20:14:37
【问题描述】:

我想知道如何使用 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 是否有任何函数来处理这个问题,或者是否需要自定义函数/正则表达式?

【问题讨论】:

    标签: javascript arrays lodash


    【解决方案1】:

    如果纯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);

    【讨论】:

      猜你喜欢
      • 2017-09-23
      • 2017-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-22
      • 1970-01-01
      • 2017-10-25
      • 1970-01-01
      相关资源
      最近更新 更多