按ID访问节点

时间:2017-02-03 12:16:03

标签: javascript jquery arrays object

这可能是一个愚蠢的问题,但......

我只是jquery使用以下方法访问对象:

obj["surveySpec"]["3"]["Survey"]["5"]["description"];

问题在于,取决于结果,它可以是不同的长度,保持不变的是42333的id

有没有办法搜索该ID并带回值?

我试过

var result2 = $.grep(obj2, function(e){ return e.id === 42333; }); 

但这不起作用

对象是:

Object
    Object
    id:1
    registration:"NA123"
    serviceVersion:"V2"
surveySpec:Array[7]
0:Object
1:Object
2:Object
3:Object
    Survey:Array[15]
    0:Object
    1:Object
    2:Object
    3:Object
    4:Object
    5:Object
    description:"survey results, 5, 2 and 3"
    id:42333
    items:Array[3]
    name:"survey results"
    value:"standard"

2 个答案:

答案 0 :(得分:1)

var test = {
  id: 1,
  items: [
    {
      id: 11,
      description: "three",
      surveys: [
        {
          id: 121,
          description: "one"
        },
        {
          id: 122,
          description: "two"
        }
      ]
    },
    {
      id: 12,
      description: "seven"
    },
    {
      id: 13,
      description: "four",
      surveys: [
        {
          id: 131,
          description: "five"
        },
        {
          id: 132,
          description: "six"
        }
      ]
    }
  ]
};

function findById(obj, id) {
  if (obj) {
    if (obj.id == id)
      return obj;
    for(var key in obj) {
      if ((typeof obj[key]).toLowerCase() != "string" && 
          (typeof obj[key]).toLowerCase() != "number") {
        var result = findById(obj[key], id);
        if (result)
          return result;
      }
    }
  }
  return null;
}
var result = findById(test, 131);
console.log("result:");
console.log(result);

答案 1 :(得分:-1)

var myVar = '';
$.each(obj["surveySpec"],function(index,object){
      $.each(obj["survey"],function(ind,innerObject){
         if(innerOject.id === 42333){
            myVar = innerObject.description;
             return false;}
      });
    });

看起来这可能就是你要找的东西。