获取唯一键值计数作为对象

时间:2017-11-26 12:20:22

标签: javascript angular typescript

我从服务器得到以下回复:

enter image description here

我想获得具有发生次数的唯一键。 采用以下格式:

0:{"name":"physics 1","count":2}
1:{"name":"chem 1","count":6}

我已经检查了How to count the number of occurrences of each item in an array?,但这不是我想要的。

2 个答案:

答案 0 :(得分:5)

这是一个es6解决方案。

const data = [{
    id: 0,
    name: 'physics 1',
    questionId: 1,
    questionNr: 1
}, {
    name: 'physics 1',
}, {
    name: 'chem 1',
}, {
    name: 'chem 1',
}, {
    name: 'chem 2',
}];

const grouped = data.reduce((groups, cur) => {
    const key = cur.name;

    groups[key] = (groups[key] || 0) + 1;

    return groups;
}, {});

const result = Object.keys(grouped).map(key => ({name: key, count: grouped[key]}));

console.log(result);

答案 1 :(得分:1)

你可以这样做:

var source = [
    {'section_name': 'test1'},
    {'section_name': 'test2'},
    {'section_name': 'test1'},
];

var temp = {};
for (var i = source.length - 1; i >= 0; i--) {
    var key = source[i].section_name;
    if (!temp[key]) {
        temp[key] = 0;
    } 

    temp[key] += 1;
}

var keys = Object.keys(temp);
var result = [];
for (var i = keys.length - 1; i >= 0; i--) {
    var key = keys[i];

    result.push({"name":key,"count":temp[key]});
}

console.log(result);