【问题标题】:Looping the array inside JSON在 JSON 中循环数组
【发布时间】:2014-11-30 11:58:00
【问题描述】:

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

的值

Employee[].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

【问题讨论】:

  • 在此处发布代码的相关部分。

标签: javascript json multidimensional-array


【解决方案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);
}

【讨论】:

  • @plbsm 感谢您的回复。但同样的事情我想让它通过我的功能发挥作用。
【解决方案2】:

问题是,这条线

        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

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

【讨论】:

    猜你喜欢
    • 2014-05-18
    • 2015-01-27
    • 1970-01-01
    • 2013-08-19
    • 2015-11-25
    • 2017-11-01
    • 2011-12-25
    • 1970-01-01
    • 2018-04-21
    相关资源
    最近更新 更多