如何使用json数据在javascript中创建2D数组

时间:2016-10-27 11:42:49

标签: javascript arrays json asp.net-mvc

我正在使用asp.net mvc框架,我有想要在2d数组中的json数据。 这是我的数据。

Json数据(输入数据)

var data=[{"ID":1,"Min":80,"Max":175},{"ID":2,"Min":90,"Max":240},{"ID":3,"Min":90,"Max":215},{"ID":4,"Min":50,"Max":120},{"ID":5,"Min":70,"Max":190},{"ID":6,"Min":50,"Max":120},{"ID":7,"Min":70,"Max":140},{"ID":8,"Min":80,"Max":160}];

我需要从Json数据中获取Min和Max值。

必填项:

data=[[80,175],[90,240],[90,215],[50,120],[70,190],[50,120],[70,140],[80,160]]

等待您的回复

4 个答案:

答案 0 :(得分:1)

您可以使用map()

执行此操作

var data=[{"ID":1,"Min":80,"Max":175},{"ID":2,"Min":90,"Max":240},{"ID":3,"Min":90,"Max":215},{"ID":4,"Min":50,"Max":120},{"ID":5,"Min":70,"Max":190},{"ID":6,"Min":50,"Max":120},{"ID":7,"Min":70,"Max":140},{"ID":8,"Min":80,"Max":160}];

var result = data.map(function(e) {
  return [e.Min, e.Max];
})

console.log(result)

答案 1 :(得分:0)

您可以使用地图(http://api.jquery.com/jquery.map/

integer

这里有一个关于小提琴http://jsfiddle.net/8TT4p/67/

的例子

答案 2 :(得分:0)

var data=[{"ID":1,"Min":80,"Max":175},{"ID":2,"Min":90,"Max":240},{"ID":3,"Min":90,"Max":215},{"ID":4,"Min":50,"Max":120},{"ID":5,"Min":70,"Max":190},{"ID":6,"Min":50,"Max":120},{"ID":7,"Min":70,"Max":140},{"ID":8,"Min":80,"Max":160}];

var data1 = [];
for(var i=0;i<data.length;i++){
  var temp = [];
  temp.push(data[i].Min);
  temp.push(data[i].Max);
  data1.push(temp);
}

现在data1是您需要的数组。

答案 3 :(得分:0)

使用Array.prototype.reduce创建结果数组的另一种解决方案:

var data=[{"ID":1,"Min":80,"Max":175},{"ID":2,"Min":90,"Max":240},{"ID":3,"Min":90,"Max":215},{"ID":4,"Min":50,"Max":120},{"ID":5,"Min":70,"Max":190},{"ID":6,"Min":50,"Max":120},{"ID":7,"Min":70,"Max":140},{"ID":8,"Min":80,"Max":160}];

var result = data.reduce(function(prev, curr) {
  prev.push([curr.Min, curr.Max]);
  return prev;
}, []);

console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}