简体   繁体   English

在多维数组中使用Underscore.js映射

[英]Using underscorejs map with multi-dimensional arrays

I am wondering if _.map is what should be used in order to accomplish the following: 我想知道_.map是否应用于完成以下任务:

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). 假设您具有以下json(“时间”的长度将始终为1。“值”的长度是未知的,但对于“数据”数组中的每个项目,该值将始终相同(在此示例中为2)。

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: 当“值”长度为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. 我尝试将每个循环放入_.map函数中,但未成功。

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. 我知道每个循环都可以使用javascript完成,但是我想知道是否有一种简单的方法可以通过_.map或另一个underscorejs集合来实现。

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 : 使用下划线,您可以使用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 ) (两个代码段都假定虽然values.length可能是未知的 ,但数组 中至少会有一个值)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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