简体   繁体   中英

Print array of arrays in Javascript

I've got an JSON Array that is of the following structure:

[
    [
        ["ABC", [
            [0, 0.139], 0.14]],
        ["DEF", [
            [0, 0.02, 0.06, 0.015], 0.115]],
        ["GHI", [
            [0, 0.0722, 0.9], 0.105]]
    ]
]

I'm stuck at the part to print it in the format

ABC
    First:0, 0.139   Final: 0.14

DEF
    First:0,0.02,0.06,0.015    Final: 0.115

This shouldn't be too hard but I'm just not able to crack it and this is what I've tried:

$.each(data, function(i){
    var vc = data[0][i];
    var cw = data[0][i].[i][1]
    var arr = [vc, cw];
    vcat.push(arr);
});

and

for(i=0; i<len;i++){
    vc.push(data[0][i]);
    for(j=0;j<len;j++){
        cw.push(data[0][i].data[j])
        }
    }
}

Both methods failed and I'm not able to figure the correct algorithm to print this tree.

It looks like this is what you're trying to do:

var o = {};

$.each(data[0][0], function () {
    o[this[0]] = {
        First: this[1][0].join(", "),
        Final: this[1][1]
    };
});

http://jsfiddle.net/qf25azhp/

For once, you're iterating over data , so you need to use data[i] - you were always accessing data[0] only (and then some other properties).

Second, the string concatenation operator in JavaScript is the + (plus), not the . .

So your codes should rather look like this:

data = data[0];
$.each(data, function(i){
    var vc = data[i][0];
    var cw = data[i][1][0][0]+" "+data[i][1][1];
    var arr = [vc, cw];
    vcat.push(arr);
});

and

data = data[0];
for(var i=0; i<len;i++){
    vc.push(data[i][0]);
}
for(var j=0;j<len;j++){
    cw.push(data[j][1][0][0]+" "+.data[j][1][1])
}

(ignoring the possibly many other problems)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM