七度&光 2011-09-09 15:42 采纳率: 22.2%
浏览 1029
已采纳

在 JavaScript 对象数组中按 id 查找对象

I've got an array:

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.]

I'm unable to change the structure of the array. I'm being passed an id of 45, and I want to get 'bar' for that object in the array.

How do I do this in JavaScript or using jQuery?

转载于:https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects

  • 写回答

29条回答 默认 最新

  • from.. 2016-02-14 21:11
    关注

    Use the find() method:

    myArray.find(x => x.id === '45').foo;
    

    From MDN:

    The find() method returns a value in the array, if an element in the array satisfies the provided testing function. Otherwise undefined is returned.


    If you want to find its index instead, use findIndex():

    myArray.findIndex(x => x.id === '45');
    

    From MDN:

    The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.


    If you want to get an array of matching elements, use the filter() method instead:

    myArray.filter(x => x.id === '45');
    

    This will return an array of objects. If you want to get an array of foo properties, you can do this with the map() method:

    myArray.filter(x => x.id === '45').map(x => x.foo);
    

    Side note: methods like find() or filter(), and arrow functions are not supported by older browsers (like IE), so if you want to support these browsers, you should transpile your code using Babel (with the polyfill).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(28条)

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容