1

I have the following arrays:

dates = ['2013-06-01', '2013-07-01', '2013-08-01', '2013-09-01', '2013-10-01', '2013-11-01']
values = [20, 10, 5, 5, 20, 25]

What I need to do is merge them into this format:

data: [
  { date: '2013-06-01', value: 20 },
  { date: '2013-07-01', value: 10 },
  { date: '2013-08-01', value: 5 },
  { date: '2013-09-01', value: 5 },
  { date: '2013-10-01', value: 20 },
  { date: '2013-11-01', value: 25 }
]
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Shpigford
  • 24,748
  • 58
  • 163
  • 252
  • 3
    This doesn't seem to have anything to do with JSON. What have you tried so far? Do you know how to iterate over arrays? – Felix Kling Nov 15 '13 at 20:52
  • First think about how to merge the data structure in javascript. JSON is just a serialization format and is a trivial last step. Can you show the code you have tried to merge these array into an array of objects? – Mike Brant Nov 15 '13 at 20:55
  • Take a look at this question: http://stackoverflow.com/questions/4856717/javascript-equivalent-of-pythons-zip-function – aga Nov 15 '13 at 20:58

4 Answers4

3

Assuming they're always the same length:

var data = [];
for (var i = 0; i < dates.length; i++) {
    var obj = {}
    obj.date = dates[i];
    obj.value = values[i];
    data.push(obj);
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

hmm. I'm sure you already thought of this. using jquery, apologize if you don't use this.

 data = jQuery.map(dates,function(v,i){
      return {'date': i, 'value': values[i]}
 }
james emanon
  • 11,185
  • 11
  • 56
  • 97
0
var data = {
  data: dates.map(function(x, i) {
    return { date: x, value: values[i] };
  })
};

Array.prototype.map is ECMAScript 5th Edition and doesn't work in < IE9. For older browsers us this polyfill

James Kyburz
  • 13,775
  • 1
  • 32
  • 33
-1

If jQuery is an option, you can try this:

http://api.jquery.com/serializeArray/

Nathan Rice
  • 3,091
  • 1
  • 20
  • 30
  • `serializeArray` is used to extract the values of a set of form control elements into an array. I don't see how this is relevant here. – Felix Kling Nov 15 '13 at 20:57