简体   繁体   English

在JSON中遍历数组

[英]Iterate through Array in JSON

I am generating a graph through JSON. 我正在通过JSON生成图形。 I want to include every element of my Array in it. 我想在其中包含数组的每个元素。 As you can see I am hard coding the array elements currently (relation[0], relation[1]). 如您所见,我目前正在对数组元素进行硬编码(relation [0],relation [1])。 I want to iterate through the whole array. 我想遍历整个数组。 How ever, I obviously can't put for loop in JSON. 但是,我显然不能在JSON中放置循环。 If I try to include only array itself (relation), my graph wont generate because the whole array is wrapped with [ ] brackets. 如果我尝试仅包括数组本身(关系),则不会生成图,因为整个数组都用[]括起来。 So instead of adding relation[0], relation[1], ..... I'd like that to be added automatically based on array size. 因此,我希望不根据关系大小自动添加关系,而不是添加关系[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]
  ]
});
for (var i = 0; i < json.length; i++) {
  var obj = json[i];

  console.log(obj.id);
}

Taken from: How do I iterate over a JSON structure? 摘自: 如何遍历JSON结构?

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

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

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

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