按属性进行JavaScript对象分组并推送到新对象

时间:2017-05-08 16:15:35

标签: javascript arrays handlebars.js javascript-objects

我需要帮助阅读一个对象,按名称分组并计算每次事件。

然后我需要将结果推送到另一个可以用把手迭代的对象。

这是我的示例对象:

var names = [ 
{ "name": "Person A" },
{ "name": "Person B" },
{ "name": "Person C" },
{ "name": "Person D" },
{ "name": "Person B" },
{ "name": "Person C" },
{ "name": "Person B" }
];

我找到了一些代码,它会遍历它并统计名称:

        for(var i = 0; i < names.length; i++) {

            if(!count[names[i].name]){
                count[names[i].name] = 0;                    
            }
            count[names[i].name]++;
        }    

这给了我以下内容:

enter image description here

我需要将这些结果推送到一个新的对象来供阅读。所以我需要数据采用这种格式:

enter image description here

这是我到目前为止所管理的内容,我正在努力将数据作为新项目推送到我的响应对象中。我不知道如何从计数对象中检索名称和总数。

// Set up the data to be returned
var names = [ 
{ "name": "Person A" },
{ "name": "Person B" },
{ "name": "Person C" },
{ "name": "Person D" },
{ "name": "Person B" },
{ "name": "Person C" },
{ "name": "Person B" }
];
var count = {};
var response = { items:[] };



        for(var i = 0; i < names.length; i++) {

            if(!count[names[i].name]){
                count[names[i].name] = 0;                    
            }
            count[names[i].name]++;
        }             


// Loop through the count object and populate response items
for(var key in count) {

    response.items.push({
            // How do i put the name and total here?
            "name": "Person A",
            "total": 12345
    });
}


console.log(count);
console.log(response);

3 个答案:

答案 0 :(得分:3)

这是你所期望的吗?

for (var key in count) {
    response.items.push({
        "name": key,
        "total": count[key]
    });
}

答案 1 :(得分:0)

你可以这样做: 像下面一样使用forin循环。

var names = [{
    "name": "Person A"
  },
  {
    "name": "Person B"
  },
  {
    "name": "Person C"
  },
  {
    "name": "Person D"
  },
  {
    "name": "Person B"
  },
  {
    "name": "Person C"
  },
  {
    "name": "Person B"
  }
];

var count = {};
for (var i = 0; i < names.length; i++) {

  if (!count[names[i].name]) {
    count[names[i].name] = 0;
  }
  count[names[i].name]++;
}

var res = [];
for(var i in count) {
  if(count.hasOwnProperty(i)) {
    res.push({name:i, total:count[i]});
  }
}
console.log(res);

答案 2 :(得分:0)

const names = [ 
{ "name": "Person A" },
{ "name": "Person B" },
{ "name": "Person C" },
{ "name": "Person D" },
{ "name": "Person B" },
{ "name": "Person C" },
{ "name": "Person B" }
]

const count = names.reduce((count, item) => (
  count[item.name]
  ? count[item.name]++
  : count[item.name] = 1
  , count)
, {})

const result = Array.from(Object.keys(count), (key) => ({ name: key, total: count[key] }))

console.log(result)