1

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.

1
  • "Also pushing does nothing" can you show what you're trying? Commented Apr 11, 2017 at 9:38

4 Answers 4

2

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}));
Sign up to request clarification or add additional context in comments.

Comments

1

Also pushing does nothing.

You are almost there, need to push this way

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

Comments

1

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"});

Comments

1

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};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.