Question

I have this Javascript json array object;

var dataJson=[ [{v:1},{v:90}],[{"v":2},{"v":"33.7000"}] ];

I want to append this array object dataJson to another object such that it looks like this;

var chartObject = {"cols": [
    {id: "t", label: "t_label", type: "number"},
    {id: "s", label: "s_label", type: "number"} 
], "rows": [
    {c: 
        [{v:1},{v:90}] //dataJson[0]
    },
    {c: 
        [{"v":2},{"v":"33.7000"}] ////dataJson[1]
    }
]};

How do I use a for loop to insert dataJson elements into chartObject? I am sorry I am quite new to javascript and can't even produce some starting code. Thank you very much for any help.

Was it helpful?

Solution

Try this:

...
  ], "rows": dataJson.map(function(row) {return {c:row};})
};

OTHER TIPS

Javascript objects are pretty amazing things. Just define a new field in chartObject as an array, and then push whatever json data you want into it. It looks you want rows to be an array of objects which have an identifier for each json object, but unless you explicitly want to name each dataJson with a string, then just use an indexed array:

chartObject["rows"] = [];

for(var i = 0; i < dataJson.length; i++) {
    chartObject["rows"].push(dataJson[0]);
}

Now you can access each piece of data with:

chartObject["rows"][index]

And each field in the data with:

chartObject["rows"][index]["v"]

Using the simple and clean way:

var chartObject = {"cols": [
    {id: "t", label: "t_label", type: "number"},
    {id: "s", label: "s_label", type: "number"} 
]};

var dataJson=[ [{v:1},{v:90}],[{"v":2},{"v":"33.7000"}] ];

chartObject["rows"] = [];   // start with empty array

// iterate over first dataJson array
for(var i = 0, len = dataJson[0].length; i < len; i++){ 
  // push in array `c` mapped to the i-th element of dataJson[0]
  chartObject["rows"].push({c : dataJson[0][i]["v"]});
}

console.log(chartObject);

DEMO

Ignore those [object Object] in DEMO

Sample Output:

{
    cols: [{
        id: "t",
        label: "t_label",
        type: "number"
    }, {
        id: "s",
        label: "s_label",
        type: "number"
    }],
    rows: [{
        c: 1
    }, {
        c: 90
    }]
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top