图表的Javascript数组格式

时间:2014-02-07 04:37:11

标签: javascript

我有两个数组

A =[1990,1991,....]
B=[a,b,c,d,e,f,...]

我想要这种格式的结果数组

Resultant=[{
                name: 1990,
                data: [a,b,c]

            },{
                name: 1991,
                data: [d,e,f]

            },...
           ]

请帮助我如何使用for循环?

4 个答案:

答案 0 :(得分:0)

根据您的(相当含糊的)要求,这将使用Array.prototype.map格式化数据:

var A = [1990,1991];
var B = ["a","b","c","d","e","f"];

var formatted = A.map(function (name, i) {
    return {
        name: name,
        data: B.slice(i*3, i*3+3)
    }
});

/*[
    {
        "name": 1990,
        "data": [
            "a",
            "b",
            "c"
        ]
    },
    {
        "name": 1991,
        "data": [
            "d",
            "e",
            "f"
        ]
    }
]*/

答案 1 :(得分:0)

假设对于A中的每个,您希望数据存储B的3个元素。我坚持使用for循环的要求。

var Resultant = [];
for (var i = 0; i < a.length; i++) {
   var data = [];
   for (var j = 0; j < 3, B.length > 0; j++) {
       data.push(B.shift());
   }

   Resultant.push({name: A[i], 'data': data});
}

答案 2 :(得分:0)

这个怎么样:

var b= ["a","b","c","d","e","f"];
var result = [1990,1991].map(function(n){ return { name:n, data: b.splice(0,3)} });

答案 3 :(得分:0)

这对我有用:

http://jsfiddle.net/s5zdD/&lt; - 请参阅jsfiddle以显示

A =[1990,1991,1992];
B=['a','b','c','d','e','f','g','h','i'];

var Resultant = jQuery.map(A, function(i,v){
// if no jQuery use:
// var Resultant = A.map(function(i,v){
    return {
        'name':A[v],
        'data': B.splice(0,3)
    }
})

console.log(Resultant);