在JSON中循环数组

时间:2014-11-30 11:58:00

标签: javascript json multidimensional-array

我正在尝试从JSON对象中获取值。以下是数据。我试图循环所有数组对象并获得

的值
  

员工[]。gradeDetails.objDetails []。SNO

以下是我目前的代码:



var Obj = {
  "Employee": [{
    "type": "grade A",
    "gradeDetails": {
      "objDetails": [{
        "sno": "100",
        "name": "",
        "desg": "writer",
        "salary": "1000000"
      }, {
        "sno": "200",
        "name": "",
        "desg": "developer",
        "salary": "1000"
      }, {
        "sno": "300",
        "name": "",
        "desg": "",
        "salary": "8000"
      }]
    }
  }]
}
var path = "Employee[].gradeDetails.objDetails[].sno";

var arrayPos = [
  [0, 0],
  [0, 1],
  [0, 2]
];
arrayPos.forEach(function(val) {
  var data = getField(Obj, path, val);
})

function getField(postObj, path, arrayPosition) {
  arrayPosition = arrayPosition.slice(Math.max(arrayPosition.length - 2, 0));
  var postObj = JSON.parse(JSON.stringify(postObj));
  var pathArray = path.split(".");
  pathArray.forEach(function(key) {
    if (key.indexOf("[]") != -1) {
      var position = 0;
      try {
        var flag = false;
        if (arrayPosition.length == 1) {
          flag = true;
        }
        if (arrayPosition.length > 1) {
          position = arrayPosition.shift();
        }
        var pos = 0;
        var arrOcc = -1;
        var occIndex = -1;
        while (pos != -1) {
          pos = path.indexOf("[]", occIndex + 1);
          arrOcc += 1;
          occIndex = pos;
        }
        if (arrOcc == 1) {
          position = arrayPosition[arrayPosition.length - 1];
          console.log("Postion" + position);
        }
        key = key.substring(0, key.indexOf("["));
        postObj = postObj[key];
        if (arrOcc == 2) {
          if (flag) {
            if (postObj.length == 2) {
              position = arrayPosition[arrayPosition.length - 1];
            }
          }
        }
        if (position == undefined) position = 0;
        postObj = postObj[position];
      } catch (e) {}
    } else {
      try {
        postObj = postObj[key];
      } catch (e) {}
    }
  });

  console.log("Result[" + arrayPosition + "]" + postObj)

  return postObj;
}




由于有三个数组对象,我期待三个不同的 sno 值,如下所示。有人可以帮我找出我在代码中做错了什么。因为我总是得到100的结果。

Result[0]100
Result[1]200
Result[2]300

我的完整代码可在此链接JSFIDDLE

中找到

2 个答案:

答案 0 :(得分:1)

我试图理解你的代码。但似乎需要时间,因为你没有评论代码向我们展示你想要做什么。我以递归的方式重新实现它(错误处理没有实现)。希望这会对你有所帮助......

var Obj = {
    "Employee": [
        {
            "type": "grade A",
            "gradeDetails": {
                "objDetails": [
                    {
                        "sno": "100",
                        "name": "",
                        "desg": "writer",
                        "salary": "1000000"
                    },
                    {
                        "sno": "200",
                        "name": "",
                        "desg": "developer",
                        "salary": "1000"
                    },
                    {
                        "sno": "300",
                        "name": "",
                        "desg": "",
                        "salary": "8000"
                    }
                ]
            }
        }
    ]
};

var path = "Employee[].gradeDetails.objDetails[].sno";
var arrayPos = [[0, 0], [0, 1], [0, 2]];

arrayPos.forEach(function (val) {
    alert(getField(Obj, path, val));
});

function getField(obj, path, arrayPosition) {
    if (path == ""){
        return obj;
    }
	var property = path.split(".")[0];
    var nextPath = path.replace(property,"").replace(".","");
    var nextObj;
    var nextArrPos;
    if (property.indexOf("[]") != -1){
        nextObj = obj[property.replace("[]","")][arrayPosition[0]];
        nextArrPos = arrayPosition.slice(1);
    } else {
        nextObj = obj[property];
        nextArrPos = arrayPosition;
    }
	return getField(nextObj,nextPath,nextArrPos);
}

答案 1 :(得分:0)

问题是,这一行     

        if (postObj.length == 2) { //should be 3 not 2
              position = arrayPosition[arrayPosition.length - 1];
        }

检查更新的fiddle

P.s.:代码有点"复杂",可能是更多结构,这可以通过调试帮助。

但如果您正在寻找更短的版本,此处此选项更短(8线解决方案),并且应该具有相同的功能

function getField(postObj, path, arrayPosition) {

    // Replaces square brakets with the Index of the passed Array(plus a dot) . 
    var newPath = path.replace(/(\[\])/gi,function(){return "." + arrayPosition.shift();});
    //creates a list of property 'namens'
    var pathElements = newPath.split(".");
    var value = postObj;
    for(var x in pathElements){
        // In each step it goes deeper into the json Object
        value = value[pathElements[x]];
    }
    return value;
}

此处fiddle

更新:只是在代码中添加了相同的评论。