我有一个数组:
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实现这一点?
当前回答
此解决方案也可能有帮助:
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,如果找到一个对象,函数将返回该对象,而不是数组。
其他回答
我真的很喜欢Aaron Digulla提供的答案,但需要保留我的对象数组,以便稍后可以迭代。所以我把它改成
var索引器={};对于(var i=0;i<array.length;i++){索引器[array[i].id]=parseInt(i);}//然后可以使用以下命令访问数组中的对象财产数组[索引器[id]].properties
最近,我不得不面对同样的事情,我需要从一个巨大的数组中搜索字符串。
经过一番搜索,我发现用简单的代码就能轻松处理:
代码:
var items = mydata.filter(function(item){
return item.word.toLowerCase().startsWith( 'gk );
})
看见https://jsfiddle.net/maheshwaghmare/cfx3p40v/4/
考虑“axesOptions”是对象数组,对象格式为{:字段类型=>2,:字段=>[1,3,4]}
function getFieldOptions(axesOptions,choice){
var fields=[]
axesOptions.each(function(item){
if(item.field_type == choice)
fields= hashToArray(item.fields)
});
return fields;
}
我认为最简单的方法是以下方法,但它在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
使用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;
});
}