简体   繁体   中英

Using underscorejs map with multi-dimensional arrays

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

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM