Javascript Object - Compress & Count in Svelte [replicate](压缩&计数)。

问题描述 投票:0回答:1

考虑这段代码是访问一个javascript对象的数据。

animalData.animal[i].type

'animal' : [ 
  {'type':'dog', 'colour':'brown'},
  {'type':'dog', 'colour':'yellow'},
  {'type':'cat', 'colour':'grey'},
  {'type':'chicken', 'colour':'orange'},
  {'type':'frog', 'colour':'green'},
  {'type':'cat', 'colour':'pink'},
  {'type':'dog', 'colour':'yellow'},
  {'type':'cat', 'colour':'grey'},
  {'type':'chicken', 'colour':'black'},
  {'type':'dog', 'colour':'yellow'}
]

使用现代JS如何将上面的内容转化为另一个对象数组,使其看起来像这样,例如,显示每个数组的计数并删除重复的对象?

[
  {'type':'dog', 'count':'4'},
  {'type':'cat', 'count':'3'},
  {'type':'chicken', 'count':'2'},
  {'type':'frog', 'count':'1'},
]
javascript javascript-objects
1个回答
1
投票

你可以 reduce 它并采取 Object values:

var data=[ {'type':'dog', 'colour':'brown'}, {'type':'dog', 'colour':'yellow'}, {'type':'cat', 'colour':'grey'}, {'type':'chicken', 'colour':'orange'}, {'type':'frog', 'colour':'green'}, {'type':'cat', 'colour':'pink'}, {'type':'dog', 'colour':'yellow'}, {'type':'cat', 'colour':'grey'}, {'type':'chicken', 'colour':'black'}, {'type':'dog', 'colour':'yellow'}];

var result = Object.values(data.reduce((acc, {type})=>{
  acc[type] = acc[type] || { type, count:0 };
  acc[type].count += 1;
  return acc;
},{}));

console.log(result);
© www.soinside.com 2019 - 2024. All rights reserved.