在JSON中迭代Array

时间:2017-03-17 09:50:26

标签: javascript json typescript

我正在通过JSON生成图表。我想在其中包含我的Array的每个元素。正如您所看到的,我正在对当前的数组元素进行硬编码(关系[0],关系[1])。我想迭代整个数组。但是,我显然无法在JSON中进行循环。如果我尝试仅包含数组本身(关系),我的图形将不会生成,因为整个数组都包含[]括号。 因此,不是添加关系[0],关系[1],.....我希望根据数组大小自动添加。

this.graph.fromJSON({
  "cells": [{
      "type": "qad.Question",
      "size": {"width": 201.8984375, "height": 125},
      "optionHeight": 30,
      "questionHeight": 45,
      "paddingBottom": 20,
      "minWidth": 150,
      "inPorts": [{"id": "in", "label": "In"}],
      "outPorts": [],
      "position": {"x": 300, "y": 38},
      "angle": 0,
      "question": objectName2,
      "options": objectCol2,
      "id": "1849d917-8a43-4d51-9e99-291799c144db",
      "z": 2
    }, relation[0],relation[1]
  ]
});

3 个答案:

答案 0 :(得分:0)

for (var i = 0; i < json.length; i++) {
  var obj = json[i];

  console.log(obj.id);
}

答案 1 :(得分:0)

取自:How do I iterate over a JSON structure?

&#13;
&#13;
var arr = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "class": "child-of-10"}];
    
for (var i = 0; i < arr.length; i++){
  document.write("<br><br>array index: " + i);
  var obj = arr[i];
  for (var key in obj){
    var value = obj[key];
    document.write("<br> - " + key + ": " + value);
  }
}
&#13;
&#13;
&#13;

答案 2 :(得分:0)

var relation= [relation[0],relation[1]];
var obj = {
  "cells": [{
      "type": "qad.Question",
      "size": {"width": 201.8984375, "height": 125},
      "optionHeight": 30,
      "questionHeight": 45,
      "paddingBottom": 20,
      "minWidth": 150,
      "inPorts": [{"id": "in", "label": "In"}],
      "outPorts": [],
      "position": {"x": 300, "y": 38},
      "angle": 0,
      "question": objectName2,
      "options": objectCol2,
      "id": "1849d917-8a43-4d51-9e99-291799c144db",
      "z": 2
    }
  ]
};
this.graph.fromJSON(obj.cells.concat(relation));