【问题标题】:Array of String to an array of JSON objects字符串数组到 JSON 对象数组
【发布时间】:2014-04-07 03:48:58
【问题描述】:

例如:

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'}]

任何帮助将不胜感激。

【问题讨论】:

标签: javascript arrays json


【解决方案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;
}, []);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 2019-06-27
    相关资源
    最近更新 更多