我有一个数组:
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.]
我无法更改阵列的结构。我收到了一个45的id,我想得到数组中该对象的“bar”。
如何在JavaScript或使用jQuery实现这一点?
我有一个数组:
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.]
我无法更改阵列的结构。我收到了一个45的id,我想得到数组中该对象的“bar”。
如何在JavaScript或使用jQuery实现这一点?
当前回答
基于公认的答案:
jQuery:
var foo = $.grep(myArray, function(e){ return e.id === foo_id})
myArray.pop(foo)
或CoffeeScript:
foo = $.grep myArray, (e) -> e.id == foo_id
myArray.pop foo
其他回答
Use:
var retObj ={};
$.each(ArrayOfObjects, function (index, obj) {
if (obj.id === '5') { // id.toString() if it is int
retObj = obj;
return false;
}
});
return retObj;
它应该按id返回一个对象。
使用Array.prototype.filter()函数。
演示:https://jsfiddle.net/sumitridhal/r0cz0w5o/4/
JSON
var jsonObj =[
{
"name": "Me",
"info": {
"age": "15",
"favColor": "Green",
"pets": true
}
},
{
"name": "Alex",
"info": {
"age": "16",
"favColor": "orange",
"pets": false
}
},
{
"name": "Kyle",
"info": {
"age": "15",
"favColor": "Blue",
"pets": false
}
}
];
过滤器
var getPerson = function(name){
return jsonObj.filter(function(obj) {
return obj.name === name;
});
}
我认为最简单的方法是以下方法,但它在Internet Explorer 8(或更早版本)上不起作用:
var result = myArray.filter(function(v) {
return v.id === '45'; // Filter out the appropriate one
})[0].foo; // Get result and access the foo property
更通用和简短
function findFromArray(array,key,value) {
return array.filter(function (element) {
return element[key] == value;
}).shift();
}
在您的示例中,Ex.varelement=findFromArray(myArray,'id',45),它将为您提供整个元素。
此解决方案也可能有帮助:
Array.prototype.grep = function (key, value) {
var that = this, ret = [];
this.forEach(function (elem, index) {
if (elem[key] === value) {
ret.push(that[index]);
}
});
return ret.length < 2 ? ret[0] : ret;
};
var bar = myArray.grep("id","45");
我将其设置为$.grep,如果找到一个对象,函数将返回该对象,而不是数组。