字符串数组到JSON对象数组

时间:2014-04-07 03:48:58

标签: javascript arrays json

例如:

var array = ['a','a','b','b','c','c','c','c','d','d','d','d','d','d'];

var ans = array.reduce(function(acc,curr){
    if(typeof acc[curr] == 'undefined') {
        acc[curr] = 1;   
    } else {
        acc[curr] += 1;
    }

    return acc;
}, {});

会给我:

ans = {'a':'2','b':'2','c':'4','d':'6'}

但我的目标是以这种格式获取它

ans = [{'word':'a','count':'2'},{'word':'b','count':'2'},{'word':'c','count':'4'},{'word':'d','count':'6'}]

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您已经拥有简洁的数据格式,但是如果您必须将其转换为更详细的版本,请尝试

var wordCount = [];
Object.keys(ans).forEach(function(word) {
    wordCount.push({
        word: word,
        count: ans[word]
    });
});

如果您想要一体化解决方案,请试试这个......

var array = ['a','a','b','b','c','c','c','c','d','d','d','d','d','d'];

var ans = array.map(function(word) {
    return { word: word, count: 1 };
}).reduce(function(p, c) {
    for (var i = 0, l = p.length; i < l; i++) {
        if (p[i].word === c.word) {
            p[i].count += c.count;
            return p;
        }
    }
    p.push(c);
    return p;
}, []);