Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am wondering if _.map is what should be used in order to accomplish the following:

Say you have the following json (length of 'time' will always be 1. Length of 'values' is unknown but it will always be the same for each item in the 'data' array (2 in this example).

data=[
  {
    time: "time1",
    values: [
      1,
      2
    ]
  },
  {
    time: "timex",
    values: [
      7,
      9
    ]
  },
  {
    time: "time_whatever",
    values: [
      11,
      22
    ]
  }
]

This is what the desired output is:

[
  {
    "x": "time1",
    "y": 1,
    "y2": 2
  },
  {
    "x": "time1",
    "y": 7,
    "y2": 9
  },
  {
    "x": "time1",
    "y": 11,
    "y2": 22
  }
]

I was able to accomplish this when the 'values' length is 1:

d = _.map(data, function(r, i) {
  return {
    "x": r.time,
    "y": r.values
  };
});

I tried putting an each loop inside the _.map function but was unsuccessful.

Not sure of map is the right answer here with a multidimensional array. I know this can be done with javascript for each loop, but I want know if there's an easy way to do this with _.map or perhaps another underscorejs collection.

Thanks

share|improve this question
    
just use another _.map inside the first _.map function. Don't look at it as "multi-dimensional" arrays, rather as nested arrays. –  Traveling Tech Guy yesterday
1  
You shouldn't have used parseInt. Those are numbers in the array, just use r.values[0]! –  Bergi yesterday
    
Thanks @Bergi. originally had the values coming in as strings. I modified the question. –  Sammy 23 hours ago

1 Answer 1

up vote 2 down vote accepted

The plain loop is probably the easiest, cleanest and fastest solution:

var d = _.map(data, function(r, i) {
  var o = {
    "x": r.time,
    "y": r.values[0]
  };
  for (var i=1; i<r.values.length; i++)
    o["y"+(i+1)] = r.values[i];
  return o;
});

With underscore, you'd use reduce:

var d = _.map(data, function(r, i) {
  return _.reduce(r.values, function(o, v, i) {
    o["y"+(i?i+1:"")] = v;
    return o;
  }, {
    "x": r.time
  });
});

(both snippet assume that while values.length might be unknown, there will be at least one value in the array)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.