我有一个数组:
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实现这一点?
当前回答
使用find()方法:
myArray.find(x => x.id === '45').foo;
来自MDN:
如果数组中的元素满足所提供的测试函数,find()方法将返回数组中的第一个值。否则返回undefined。
如果要查找其索引,请使用findIndex():
myArray.findIndex(x => x.id === '45');
来自MDN:
findIndex()方法返回数组中满足所提供测试函数的第一个元素的索引。否则返回-1。
如果要获取匹配元素的数组,请改用filter()方法:
myArray.filter(x => x.id === '45');
这将返回一个对象数组。如果要获取foo财产数组,可以使用map()方法:
myArray.filter(x => x.id === '45').map(x => x.foo);
附带说明:旧浏览器(如IE)不支持find()或filter()和arrow函数等方法,因此如果您想支持这些浏览器,应该使用Babel(带有polyfill)来转换代码。
其他回答
更通用和简短
function findFromArray(array,key,value) {
return array.filter(function (element) {
return element[key] == value;
}).shift();
}
在您的示例中,Ex.varelement=findFromArray(myArray,'id',45),它将为您提供整个元素。
以下是我将如何在纯JavaScript中实现它,以我所能想到的在ECMAScript 3或更高版本中工作的最简单的方式。一旦找到匹配项,它就会返回。
var getKeyValueById = function(array, key, id) {
var testArray = array.slice(), test;
while(test = testArray.pop()) {
if (test.id === id) {
return test[key];
}
}
// return undefined if no matching id is found in array
return;
}
var myArray = [{'id':'73', 'foo':'bar'}, {'id':'45', 'foo':'bar'}]
var result = getKeyValueById(myArray, 'foo', '45');
// result is 'bar', obtained from object with id of '45'
使用jQuery的过滤方法:
$(myArray).filter(function()
{
return this.id == desiredId;
}).first();
这将返回具有指定Id的第一个元素。
它还具有良好的C#LINQ格式的优点。
正如其他人所指出的,.find()是在数组中查找一个对象的方法。但是,如果无法使用此方法找到对象,则程序将崩溃:const myArray=[{'id':'73','o':'bar'},{'id':'45','o':'bar'}];const res=myArray.find(x=>x.id=='100').foo;//噢!/*错误:“Uncaught TypeError:无法读取未定义的属性'foo'”或在较新的chrome版本中:Uncaught TypeError:无法读取未定义的的财产(读取“foo”)*/
这可以通过在使用.foo之前检查.find()的结果是否已定义来解决。Modern JS允许我们通过可选链接轻松完成这一点,如果找不到对象,则返回undefined,而不是崩溃代码:
const myArray=[{'id':'73','o':'bar'},{'id':'45','o':'bar'}];const res=myArray.find(x=>x.id=='100')?。foo;//没有错误!console.log(res);//找不到对象时未定义
ECMAScript 2015(JavaScript ES6)提供find()数组上的方法:
var myArray=[{id:1,name:“bob”},{id:2,名称:“dan”},{id:3,名称:“barb”},]//抓取与id“2”匹配的Array项var item=myArray.find(item=>item.id===2);//打印console.log(item.name);
它在没有外部库的情况下工作。但是,如果您想要更旧的浏览器支持,您可能需要包含此polyfill。