如何对字典数组中的内容进行分组?

时间:2019-05-28 14:27:58

标签: javascript arrays reactjs algorithm sorting

我知道可以从后端轻松解决此问题,但很好奇是否有使用js从前端解决此问题的有效方法。

我有一个数组

[
 {  
    id: 11
    ruleDesc: "rule 1 "
 },
{  
    id: 15
    ruleDesc: "rule 2 "
 },
{  
    id: 12
    ruleDesc: "rule 3 "
 },
{  
    id: 11
    ruleDesc: "rule 4 "
 },
{  
    id: 11
    ruleDesc: "rule 5 "
 },

]

我期望的是

[
  {  
        id: 11
        ruleDesc: "rule 1 "
        ruleDesc: "rule 4 "
        ruleDesc: "rule 5 "
     },
{  
        id: 12
        ruleDesc: "rule 3 "
     },
{  
        id: 15
        ruleDesc: "rule 2 "
     },
]

2 个答案:

答案 0 :(得分:1)

您需要为同一组创建ruleDesc数组。因为对象不能具有相同的键。

您可以使用reduce()获取对象,然后使用Object.values获取数组。

const arr = [ { id: 11, ruleDesc: "rule 1 " }, { id: 15, ruleDesc: "rule 2 " }, { id: 12, ruleDesc: "rule 3 " }, { id: 11, ruleDesc: "rule 4 " }, { id: 11, ruleDesc: "rule 5 " } ]

const res = arr.reduce((ac,{id,ruleDesc}) => {
  ac[id] = ac[id] || {id,ruleDesc:[]}
  ac[id].ruleDesc.push(ruleDesc);
  return ac;
},{})
console.log(Object.values(res))

答案 1 :(得分:1)

这类似于Masheer Ali的回答,但我认为减少的程度更好一些:

const transform = arr => Object .values (arr .reduce ((a, {id, ruleDesc}) => 
  ({...a, [id]: {id, ruleDesc: [...( (a [id] || {}) .ruleDesc || [] ), ruleDesc]}}),
  {}
))

const rules = [{id: 11, ruleDesc: "rule 1 "}, {id: 15, ruleDesc: "rule 2 "}, {id: 12, ruleDesc: "rule 3 "}, {id: 11, ruleDesc: "rule 4 "}, {id: 11, ruleDesc: "rule 5 "}]

console .log (
  transform (rules)
)

优点之一是,如果您有其他要合并的属性,这只是一个小调整:

const transform = arr => Object .values (arr .reduce ((a, {id, ruleDesc, ...rest}) => 
  ({...a, [id]: {...(a[id] || {}), id,  ruleDesc: [...((a[id] || {}).ruleDesc || []) , ruleDesc], ...rest}}),
  {}
))