如何按数据类型映射和分组数组数据?

How can I map and group array data by datatype?

我有一组数据要导入到 React 应用程序中 -

const knowledgeData = [
  {
    id: 'connect',
    catTitle: 'Connectivity',
    subTitle:'Very Slow - Loader Stays on',
    subData:'<><p>Lorem Ipsum Solar denar.</p><p>lorem imsum again.</p></>'

  },
  {
    id: '`cms`',
    catTitle: 'CMS ISSUES',
    subTitle:'UNABLE TO LOG IN',
    subData:'<><p>Lorem Ipsum Solar denar.</p><p>lorem imsum again.</p></>'

  },
  {
    id: '`cms`',
    catTitle: 'CMS ISSUES',
    subTitle:'UNABLE TO PRINT REPORT',
    subData:'<><p>Lorem Ipsum Solar denar.</p><p>lorem imsum again.</p></>'

  },
  {
    id: '`cms`',
    catTitle: 'CMS ISSUES',
    subTitle:'Unable To Covert a PDF',
    subData:'<><p>Lorem Ipsum Solar denar.</p><p>lorem imsum again.</p></>'

  },
  {
    id: 'app',
    catTitle: 'Staff App Issues',
    subTitle:'Unable to access photos',
    subData:'<><p>Lorem Ipsum Solar denar.</p><p>lorem imsum again.</p></>'

  },
];

数据用于员工 wiki - 我需要以分组方式显示数据 - 按 ID 分组,因为每个数据组在设计中都被分隔到自己的网格中 - 例如,所有 CMS 相关问题都是以 CMS 问题等标题分组

我已经得到了 map 语句,但我对解决问题的方法感到困惑 -

returnFields = () =>{
  
    this.state.knowledgeData.map((data,i) => {
     //for each datatype:(
        //return(
          //HTML containing mapped data here with group title wrap

          
     
    }); 
}

谁能在这里提出一个好的解决方案?

你得到了你想要的结果吗?

const result = knowledgeData.reduce((acc, cur) => {
  acc[cur.id] = [...(acc[cur.id] || []), cur];

  return acc;
}, {});

我建议为您的输入数组创建一个 groupBy() 函数,然后您可以按所需的 属性.

进行分组

groupBy 函数使用 Array.reduce() 创建一个分组对象,每个 id 值都有一个对象数组,在本例中为 connectcmsapp

const knowledgeData = [ { id: 'connect', catTitle: 'Connectivity', subTitle:'Very Slow - Loader Stays on', subData:'<><p>Lorem Ipsum Solar denar.</p><p>lorem imsum again.</p></>'  }, { id: '`cms`', catTitle: 'CMS ISSUES', subTitle:'UNABLE TO LOG IN', subData:'<><p>Lorem Ipsum Solar denar.</p><p>lorem imsum again.</p></>'  }, { id: '`cms`', catTitle: 'CMS ISSUES', subTitle:'UNABLE TO PRINT REPORT', subData:'<><p>Lorem Ipsum Solar denar.</p><p>lorem imsum again.</p></>'  }, { id: '`cms`', catTitle: 'CMS ISSUES', subTitle:'Unable To Covert a PDF', subData:'<><p>Lorem Ipsum Solar denar.</p><p>lorem imsum again.</p></>'  }, { id: 'app', catTitle: 'Staff App Issues', subTitle:'Unable to access photos', subData:'<><p>Lorem Ipsum Solar denar.</p><p>lorem imsum again.</p></>'  }, ];

function groupBy(input, key) {
    return input.reduce((acc, el) => { 
        acc[el[key]] = acc[el[key]] || [];
        acc[el[key]].push(el);
        return acc;
    }, {});
}

const grouped = groupBy(knowledgeData, 'id');

console.log('Result:');
for(let key in grouped) {
    console.log('Group:', key);
    console.log(grouped[key]);
}
.as-console-wrapper { max-height: 100% !important; }