Loop through multiple array and keep count of each element

自作多情 提交于 2019-12-02 11:20:51

You can use reduce like this:

var a = [{"Name":"TestPost","Id":123,"ProductHandlingTypes":[{"Id":1,"Name":"Type1"},{"Id":2,"Name":"Type2"}]},{"Name":"TestPost2","Id":124,"ProductHandlingTypes":[{"Id":3,"Name":"Type3"},{"Id":1,"Name":"Type1"}]}];

var b = a.reduce((acc, cur) => {
  cur.ProductHandlingTypes.map(({Name}) => Name).forEach(n => acc[n] = (acc[n] || 0) + 1);
  return acc;
}, {})

console.log(b)

It loops through your array and increments Type n values or creates them is they don't exist.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!