我有一个数组:
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实现这一点?
当前回答
您可以使用map()函数轻松实现这一点:
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
var found = $.map(myArray, function(val) {
return val.id == 45 ? val.foo : null;
});
//found[0] == "bar";
工作示例:http://jsfiddle.net/hunter/Pxaua/
其他回答
考虑“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;
}
由于您已经在使用jQuery,因此可以使用grep函数来搜索数组:
var result = $.grep(myArray, function(e){ return e.id == id; });
结果是找到项的数组。如果您知道对象始终存在,并且它只出现一次,那么只需使用result[0].foo获取值。否则,应检查结果数组的长度。例子:
if (result.length === 0) {
// no result found
} else if (result.length === 1) {
// property found, access the foo property using result[0].foo
} else {
// multiple items found
}
最近,我不得不面对同样的事情,我需要从一个巨大的数组中搜索字符串。
经过一番搜索,我发现用简单的代码就能轻松处理:
代码:
var items = mydata.filter(function(item){
return item.word.toLowerCase().startsWith( 'gk );
})
看见https://jsfiddle.net/maheshwaghmare/cfx3p40v/4/
查找数组索引的方法:
index = myArray.map((i) => i.id).indexOf(value_of_id);
item = myArray[index];
另一种解决方案是创建查找对象:
var lookup = {};
for (var i = 0, len = array.length; i < len; i++) {
lookup[array[i].id] = array[i];
}
... now you can use lookup[id]...
如果需要进行多次查找,这一点尤其有趣。
这将不需要更多的内存,因为ID和对象将被共享。