重新排列javascript数组/对象

时间:2015-03-10 16:36:38

标签: javascript arrays json sorting object

我正在尝试重新安排:

[
    {"Appointment":"6","Converted":"0","Lead":"9","Qualified":"0","Dead":"0"},
    {"Appointment":"1","Converted":"0","Lead":"1","Qualified":"0","Dead":"0"},
    {"Appointment":"1","Converted":"0","Lead":"0","Qualified":"0","Dead":"0"}
]

要:

[
    {"name":"Appointment", "data":[6,1,1]},
    {"name":"Converted", "data":[0,0,0]},
    {"name":"Lead", "data":[9,1,0]},
    {"name":"Qualified", "data":[0,0,0]},
    {"name":"Dead", "data":[0,0,0]}
]

我已经设法通过为(obj中的var prop)循环来获取具有正确名称的5个数组,但我想知道如何实现转换数据部分。也许是一厢情愿的想法,但是有一种比在循环中循环更简单的方法!?

解决方案必须是动态的...可能有3个数组,如我的例子或更多或更少。但是,属性的​​数量总是为5,如示例所示。

2 个答案:

答案 0 :(得分:1)

使结果成为一个对象,其键是名称,因为它更容易查找:

var result = {};
for (var key in input[0]) {
    result[key] = [];
}
for (var i = 0; i < input.length; i++) {
    var obj = input[i];
    for (key in obj) {
        result[key].push(parseInt(obj[key], 10));
    }
}

如果您确实需要将结果作为对象数组,则可以转换result

var result_array = [];
for (var name in result) {
    result_array.push({name: name, data: result[name]});
}

答案 1 :(得分:1)

你可以将对象分组,然后放入数组...就像小提琴......

http://jsfiddle.net/u7xLnmuh/

var data = [
    {"Appointment":"6","Converted":"0","Lead":"9","Qualified":"0","Dead":"0"},
    {"Appointment":"1","Converted":"0","Lead":"1","Qualified":"0","Dead":"0"},
    {"Appointment":"1","Converted":"0","Lead":"0","Qualified":"0","Dead":"0"}
]


function groupByKey(data){
    var grouped = {};
    var result = [];

    data.forEach(function(row){

        for(var property in row){

            if(!(property in grouped)){
                grouped[property] = [];
            }

            grouped[property].push(+row[property]);            
        }        
    });

    for(var property in grouped){
        result.push({
            name: property,
            data: grouped[property]
        });
    }

    return result;

}


var groupedData = groupByKey(data));

此解决方案对输入的任何数据集都是通用的