简体   繁体   中英

Dynamically generate array of objects - Javascript

I'm adapting a D3 pie chart to my own work and want to dynamically recreate the data structure seen below.

    var data = [
{"label":"Colorectale levermetastase (n=336)", "value":74}, 
{"label": "Primaire maligne levertumor (n=56)", "value":12},
{"label":"Levensmetatase van andere origine (n=32)", "value":7}, 
{"label":"Beningne levertumor (n=34)", "value":7}];

I've tried

data += {"label": cat_row, "value": +freq_row};

but it doesn't give the desired results. Also pushing does nothing.

data["label"] = cat_row;

The line above just seems to overwrite the each iteration.

Any guidance would be much appreciated.

There are few ways to dynamically recreate the data structure.

To add a new element to the end of the array:

 data.push({"label": cat_row, "value": +freq_row});

or

data[data.length] = {"label": cat_row, "value": +freq_row};

To add a new element to the beginning of the array:

data.unshift({"label": cat_row, "value": +freq_row}));

Also pushing does nothing.

You are almost there, need to push this way

var data = [];
data.push( {"label": cat_row, "value": freq_row } );

If you want an array you need to use Array#push() . This will add the element in parameter to the end of the array

var data = [];
data.push({label:"test"});

Do you want to add data to your array or do you want to replace the data?

to add data to the array use:

data.push({"label": cat_row, "value": +freq_row})

to replace data in your array:

var index = 0;
data[index] = {"label": cat_row, "value": +freq_row};

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