1

我有一个看起来像这样的二维 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 的对象。

那么我如何将其作为二维选项卡进行迭代呢?

[编辑]

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

4

2 回答 2

3

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);
  }
}
于 2018-05-07T10:59:40.790 回答
1

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);

  }
}

于 2018-05-07T12:54:20.170 回答