0

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

3
  • just use another _.map inside the first _.map function. Don't look at it as "multi-dimensional" arrays, rather as nested arrays. Commented Sep 10, 2014 at 22:30
  • 1
    You shouldn't have used parseInt. Those are numbers in the array, just use r.values[0]! Commented Sep 10, 2014 at 22:52
  • Thanks @Bergi. originally had the values coming in as strings. I modified the question. Commented Sep 10, 2014 at 23:30

1 Answer 1

2

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)

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.