迭代二维json的正确方法

时间:2018-05-07 10:16:04

标签: javascript for-loop foreach array-map for-of-loop

我有一个二维json,看起来像:

[[{"ID":1,"Name":"....","Ct":123, "Time":"2018-05-07T00:00:00"},
{"ID":2,"Name":"....","Ct":123, "Time":"2018-05-07T00:01:00"}],
[{"ID":3,"Name":"....","Ct":123, "Time":"2018-05-07T00:02:00"},
{"ID":4,"Name":"....","Ct":123, "Time":"2018-05-07T00:03:00"}]]

它是从C#对象序列化的。无论如何,我试着迭代这个json,如:

for (var key in data) // first loop
{
  var item = data[key];
  for (var key2 in item) // second loop
  {
    // some code...
  }
}

第一个循环应该迭代两次:在第一次迭代期间,第二个循环应该迭代两个ID为1和2的对象;在第二次迭代中,ID为3和4的对象。

我猜问题是第一个循环没有Key,因为第一个循环只迭代一次而第二个循环遍历ID为1,2,3,4的对象。

我怎样才能将其作为二维标签进行迭代呢?

[编辑]

我在迭代内部第二个循环时犯了一个错误,看起来它没有迭代。上面的解决方案是正确的。

2 个答案:

答案 0 :(得分:2)

for循环应该可以工作,但你也可以使用maps / forEach / for-of来迭代数组:

var input = [
  [{"ID":1,"Name":"....","Ct":123, "Time":"2018-05-07T00:00:00"},
    {"ID":2,"Name":"....","Ct":123, "Time":"2018-05-07T00:01:00"}],
  [{"ID":3,"Name":"....","Ct":123, "Time":"2018-05-07T00:02:00"},
   {"ID":4,"Name":"....","Ct":123, "Time":"2018-05-07T00:03:00"}]
];

input.map(outElem => {
  console.log('======== outter ========');
  outElem.map(inElem => {
    console.log('======== inner ========');
    console.log(inElem.ID);
  });
});

// Output:
======== outter ========
======== inner ========
1
======== inner ========
2
======== outter ========
======== inner ========
3
======== inner ========
4

或者forEach:

input.forEach(outElem => {
  console.log('======== outter ========');
  outElem.forEach(inElem => {
    console.log('======== inner ========');
    console.log(inElem.ID);
  });
});

或者是:

for (const outElem of input) {
  console.log('======== outter ========');
  for (const inElem of outElem) {
    console.log('======== inner ========');
    console.log(inElem.ID);
  }
}

答案 1 :(得分:0)

var data = [
	[{
			"ID": 1,
			"Name": "....",
			"Ct": 123,
			"Time": "2018-05-07T00:00:00"
		},
		{
			"ID": 2,
			"Name": "....",
			"Ct": 123,
			"Time": "2018-05-07T00:01:00"
		}
	],
	[{
			"ID": 3,
			"Name": "....",
			"Ct": 123,
			"Time": "2018-05-07T00:02:00"
		},
		{
			"ID": 4,
			"Name": "....",
			"Ct": 123,
			"Time": "2018-05-07T00:03:00"
		}
	]
];

for (var key in data) // first loop
{
  var item = data[key];
  console.log('======== outter ========');
  for (var key2 in item) // second loop
  {
      console.log('======== inner ========');
      console.log(item[key2].ID);

  }
}