3

I have 2 arrays

var labels = ["DESKTOP","MOBILE","TABLET"]

var chartData = ["100","10","15"]

And I need to combine these into one array with objects

    var myData = [{
    label: DESKTOP,
    value: 100},
{
    label: MOBILE,
    value: 10},
{
    label: TABLET,
    value: 15},
    ];

So far I've pushed labels into an array with new object

$.each(labels, function (index, item) {                            
      myData.push({
           label: item,
           value: ''
      });     
 });

I've done empty value, and now can't push value to an object in array. Just can't figure out how to push each value to new object in array. Help is much appreciated.

Thanks.

Data is sample only.

2 Answers 2

3

var labels = ["DESKTOP", "MOBILE", "TABLET"];
var chartData = ["100", "10", "15"];
var myData = [];

labels.forEach(function(e, i) {
  myData.push({
    label: e,
    data: chartData[i]
  })
})

document.write(JSON.stringify(myData));

Sign up to request clarification or add additional context in comments.

Comments

0

How about:

$.each(labels, function (index, item) {                            
  myData.push({
       label: item,
       value: chartData[index]
  });     
 });

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.