开发者

how to construct a json object using info from several javascript arrays

I have two js arrays already, say: names and values (with the same length), now I would like to construct a json object in certain format? For example:

 names = ["label1","label2","label3"];
 values = [[[0,1],[1,9],[2,10]],[[0,89],[1,91],[2,1]],[[0,1],[1,9],[2,10]]];

I would like to have a json array data_spec in this format:

 [{
    label:"label1",
    data:[[0,1],[1,9],[2,10]]
  },
  {
    lab开发者_StackOverflowel:"label2",
    data:[[0,89],[1,91],[2,1]]
  },
  {
    label:"label3",
    data:[[0,1],[1,9],[2,10]]
  }]

Could anyone tell one how? Thanks a lot!


For a bit of variety and a check,

var data_spec = [];
if (names.length != values.length) {
    // panic, throw an exception, log an error or just return an empty array
} else {
    for (var i=0, name; name = names[i]; i++) { // assuming a non-sparse array
        data_spec[i] = { 
            label : name, 
            data  : values[i] 
        };
    }
}

That is, non-sparse and not containing anything else that would evaluate to false.

If your framework has an each function added to Array and you don't care about performance,

var data_spec = [];
names.each(function(name) {
    data_spec.push({ label : name, data : values[names.indexOf(name)] });
});

If your framework is a clean one like Dojo and puts it somewhere else (ex is Dojo),

var data_spec = [];
dojo.forEach(names, function(name) {
    data_spec.push({ label : name, data : values[names.indexOf(name)] });
});

If your framework has an each function that returns an Array of identical length with the results of every operation at their expected position,

var data_spec = arrayOfResultsEach(names, function(name) {
    return { label : name, data : values[names.indexOf(name)] };
});

These are just for illustration, indexOf inside loops of arbitrary length is a major code smell.


Just use a loop (make sure the two arrays are of same length)

result = [];
for(var i=0, len=names.length; i < len; i++) {
    result.push({label: names[i], data: values[i]});
}


    var myArray = 
    [{
        "label": "label1",
        "data" : 
        {
            "0": "1",
            "1": "9",
            "2": "10"
        }
    },

    {
        "label": "label2",
        "data" : 
        {
            "0": "89",
            "1": "91",
            "2": "1"
        }
    },

    {
        "label": "label3",
        "data" : 
        {
            "0": "1",
            "1": "9",
            "2": "10"
        }
    }];

    alert(myArray[0].data[2]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜