2

I am trying to create a data object that looks like this:

var data = [{"label":"Category A", "value":20}, 
              {"label":"Category B", "value":50}, 
              {"label":"Category C", "value":30}];

I have a loop so far (below) that builds it as a string, but I am wondering if there is a better way to build this using some javascript objects:

for (i = 0; i < doughnutData.length; i += 3) {
    if (doughnutData[i] != "" && (i != doughnutData.length - 1)) {
        var dataValue = parseInt(doughnutData[i + 1], 10);
        chartData.push('{"label":"' + doughnutData[i] + '", "value":' + dataValue + '}');
    }
} 
2
  • 7
    Why a string? chartData.push({label: doughnutData[i], value: dataValue}); Commented Aug 12, 2015 at 19:26
  • Cool, didn't know you could do it like that (new to javascript) Commented Aug 12, 2015 at 19:28

1 Answer 1

4

You've actually done a bit more work pushing a stringified version - you can easily create an object:

chartData.push({label: doughnutData[i], value: dataValue})
Sign up to request clarification or add additional context in comments.

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.