我想遍历一个对象数组并返回另一个对象数组,该对象数组具有基于像哈希表这样的特定属性值类型的记录数。
例如:
Array1=[{"name":"Pam", "role":"ceo"}, {"name":"Joel", "role":"engineer"}, {"name":"Mary", "role":"ceo"}, {"name":"Alice", "role":"analyst"}, {"name":"John", "role":"analyst"}, {"name":"Nick", "role":"engineer"}, {"name":"Sam", "role":"analyst"}]
Array2 = [{key: "ceo", count: 2}, {key: "engineer", count: 2}, {key: "analyst", count:3}]
我需要一个从Array1生成Array2的代码。非常感谢您的帮助:)
解决了我的问题,谢谢
答案 0 :(得分:1)
应该很容易理解。检查代码。
let array1 = [
{ name: "Pam", role: "ceo" },
{ name: "Joel", role: "engineer" },
{ name: "Mary", role: "ceo" },
{ name: "Alice", role: "analyst" },
{ name: "John", role: "analyst" },
{ name: "Nick", role: "engineer" },
{ name: "Sam", role: "analyst" }
];
let obj = {};
array1.forEach(entry => (obj[entry.role] = (obj[entry.role] || 0) + 1));
let array2 = [];
for (role in obj) {
array2.push({ key: role, count: obj[role] });
}
console.log(array2);
答案 1 :(得分:0)
您可以使用reduce
将对象数组分组为单个对象。使用Object.values
将对象转换回数组。
let Array1 = [{"name":"Pam", "role":"ceo"}, {"name":"Joel", "role":"engineer"}, {"name":"Mary", "role":"ceo"}, {"name":"Alice", "role":"analyst"}, {"name":"John", "role":"analyst"}, {"name":"Nick", "role":"engineer"}, {"name":"Sam", "role":"analyst"}]
let Array2 = Object.values(Array1.reduce((c, {role}) => {
c[role] = c[role] || {key: role,count: 0};
c[role].count++;
return c;
}, {}));
console.log(Array2);
答案 2 :(得分:0)
您必须创建一个哈希图/对象来跟踪唯一计数。
例如:
let Array1=[{"name":"Pam", "role":"ceo"}, {"name":"Joel", "role":"engineer"}, {"name":"Mary", "role":"ceo"}, {"name":"Alice", "role":"analyst"}, {"name":"John", "role":"analyst"}, {"name":"Nick", "role":"engineer"}, {"name":"Sam", "role":"analyst"}]
let hashMap = {}
for(var employee of Array1){
//if that role exists
if(employee.role in hashMap ){
//up the prev count
hashMap[employee.role] = hashMap[employee.role] + 1;
}else{
hashMap[employee.role] = 1;
}
}
//now we will iterate through those keys of the Map and format it for Array 2
let outputArray = []
Object.keys(hashMap).forEach(key => {
outputArray.push({
key,
count: hashMap[key]
})
})
console.log(outputArray)
答案 3 :(得分:0)
这里有两个变体,分别是对象和数组。 (需要ES6)
let arr = [
{"name":"Pam", "role":"ceo"},
{"name":"Joel", "role":"engineer"},
{"name":"Mary", "role":"ceo"},
{"name":"Alice", "role":"analyst"},
{"name":"John", "role":"analyst"},
{"name":"Nick", "role":"engineer"},
{"name":"Sam", "role":"analyst"}
]
let objResult = arr.reduce((acc, obj) => {
acc[obj.role] = (acc[obj.role] || 0) + 1;
return acc;
}, {});
console.log(objResult);
let arrResult = Object.keys(objResult).map(k => ({[k]: objResult[k]}));
console.log(arrResult)