假设我们有一个对象数组,其中包含一些有关某些用户的数据,如下所示:
const arr = [ { "name":"aaa", "id":"2100", "designation":"developer" }, { "name":"bbb", "id":"8888", "designation":"team lead" }, { "name":"ccc", "id":"6745", "designation":"manager" }, { "name":"aaa", "id":"9899", "designation":"sw" } ];
我们需要编写一个包含一个这样的数组的JavaScript函数。然后,我们的函数应返回一个新对象,该对象包含映射到包含该特定name属性的对象计数的所有name属性值。
因此,对于上述数组,输出应类似于-
const output = { "aaa": 2, "bbb": 1, "ccc": 1 };
为此的代码将是-
const arr = [ { "name":"aaa", "id":"2100", "designation":"developer" }, { "name":"bbb", "id":"8888", "designation":"team lead" }, { "name":"ccc", "id":"6745", "designation":"manager" }, { "name":"aaa", "id":"9899", "designation":"sw" } ]; const countNames = (arr = []) => { const res = {}; for(let i = 0; i < arr.length; i++){ const { name } = arr[i]; if(res.hasOwnProperty(name)){ res[name]++; } else{ res[name] = 1; }; }; return res; }; console.log(countNames(arr));
输出结果
控制台中的输出将是-
{ aaa: 2, bbb: 1, ccc: 1 }