当我访问JSON数组中的特定值时

时间:2017-03-14 09:26:05

标签: javascript json

这是我的JSON数据数组。我想从名为UserID的JSON数组中访问jsonResult字段。请建议我正确解决上面的JSON问题。

[ 
  {
    "UserRelationshipID":1,
    "SubordinateUserID":1014,
    "UserID":3,
    "UserRelationshipTypeID":1
  }
]

4 个答案:

答案 0 :(得分:1)

您的JSON对象

var jsonResult = [{
  "UserRelationshipID":1,
  "SubordinateUserID":1014,
  "UserID":3,
  "UserRelationshipTypeID":1
},{
  "UserRelationshipID":2,
  "SubordinateUserID":1015,
  "UserID":4,
  "UserRelationshipTypeID":1
}];

<强>的JavaScript

for(var i=0;i<jsonResult.length;i++){
  console.log(jsonResult[i]);                    /*Access Object*/
  console.log("User ID" + jsonResult[i].UserID); /*Access Only UserID*/
}

<强>的jQuery

$(jsonResult).each(function(Key,Value){
  console.log(Value);           /*Access Object*/
  console.log(Value.UserID);    /*Access Only UserID*/
});

答案 1 :(得分:0)

array().getJSONObject(0).get("UserID")

答案 2 :(得分:0)

假设您有对象数组,则可以获取用户ID,如下所示。之后,您可以根据需要将结果保存在变量或其他内容中,而不是安慰结果。

var jsonResult = [ {"UserRelationshipID":1,"SubordinateUserID":1014,"UserID":3,"UserRelationshipTyp‌​eID":1}, {"UserRelationshipID":1,"SubordinateUserID":2537,"UserID":3,"UserRelationshipTyp‌​eID":1}, {"UserRelationshipID":1,"SubordinateUserID":3,"UserID":4,"UserRelationshipTypeID‌​":1}, {"UserRelationshipID":1,"SubordinateUserID":7,"UserID":4,"UserRelationshipTypeID‌​":1}, {"UserRelationshipID":1,"SubordinateUserID":6,"UserID":2537,"UserRelationshipTyp‌​eID":1}, {"UserRelationshipID":1,"SubordinateUserID":3,"UserID":2537,"UserRelationshipTyp‌​eID":1}]

for(var i=0; i<jsonResult.length; i++){
  console.log(jsonResult[i].UserID)
}

答案 3 :(得分:0)

你有一个对象数组和一个对象。您打算对数组中对象的UserID区域执行某些操作。你可以这样做:

yourarray[0].UserID

其中yourarray是您的JSON,0是第一个对象的索引,UserID是该对象的UserID成员。如果您想迭代数组并访问UserID,那么

for (var index in yourarray) {
    //Do something with yourarray[index].UserID
}

更一般地说:

function iterateArray(arr, field) {
    for (var index in arr) {
        //Do something with arr[index][field]
    }
}

并将其称为:iterateArray(yourarray, "UserID")