任何人都可以让我知道如何从jQuery / Javascipt中的以下数组对象获取“ID”的值为6。
[Object {name="mode", value="Add"},
Object {name="test", value="abc"},
Object {name="ID", value="6"}]
答案 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
的对象(假设总有一个这样的对象) ),然后返回其值。
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;
此代码不完整,您可能需要检查filter
结果长度或制作通用方法:
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;
答案 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
}
});