如何在jQuery中获取数组对象的值

时间:2016-08-10 09:35:57

标签: jquery

任何人都可以让我知道如何从jQuery / Javascipt中的以下数组对象获取“ID”的值为6。

[Object {name="mode", value="Add"}, 
 Object {name="test", value="abc"}, 
 Object {name="ID", value="6"}]

3 个答案:

答案 0 :(得分:0)

您可以循环数组并在对象中搜索ID

// your object
var arr = [
    {name: "mode", value: "Add"}, 
    {name: "test", value: "abc"}, 
    {name: "ID", value: "6"}
];

// the default value, whenever 'ID' is not found
var value = null;

// loop the array and search
for( var i = 0; i < arr.length; i++ ) {
    if( arr[i].name === "ID" ) {
        value = arr[i].value;
    }
}

// your result :)
console.log(value);

答案 1 :(得分:0)

您需要遍历数组并找到具有所需name的对象 最简单的方法是使用Array.prototype.filter - 您可以过滤数组,只留下name等于ID的对象(假设总有一个这样的对象) ),然后返回其值。

&#13;
&#13;
var arr = [{ "name": "mode", "value": "Add" }, { "name": "test", "value": "abc" }, { "name": "ID", "value": "6" }];

// pre-ES6 syntax
var id = arr.filter(function(x) { return x.name === 'ID'; })[0].value; 
console.log(id);

// ES6 syntax
var id = arr.filter(x => x.name === 'ID')[0].value;
console.log(id);
&#13;
&#13;
&#13;

此代码不完整,您可能需要检查filter结果长度或制作通用方法:

&#13;
&#13;
var arr = [{ "name": "mode", "value": "Add" }, { "name": "test", "value": "abc" }, { "name": "ID", "value": "6" }];
   
function getParameter(obj, param) {
  var foundParams = obj.filter(function(x) { 
    return x.name === param 
  });
  
  if (foundParams.length == 0)  
    return null;
  
  if (foundParams.length > 1)
    throw new Error('Invalid object: more than one parameter ' + param);
  
  return foundParams[0].value;
}

console.log(getParameter(arr, 'ID'));
console.log(getParameter(arr, 'test'));
console.log(getParameter(arr, 'mode'));
console.log(getParameter(arr, 'notexists'));
&#13;
&#13;
&#13;

答案 2 :(得分:0)

ar your_array =[
 {name :"mode", value:"Add"}, 
 {name :"test", value:"abc"}, 
 {name :"ID", value:"6"}
 ];

$.each( your_array, function( key, value ) {

  if(key=="ID")
  {
  var your_Value = value; //6
  }
});