EvgenyK
EvgenyK

Reputation: 65

add value to object in array javascript

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.

Upvotes: 3

Views: 6244

Answers (2)

John
John

Reputation: 770

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

Upvotes: 3

RJM
RJM

Reputation: 1178

How about:

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

Upvotes: 0

Related Questions