local-host 2011-09-09 15:42 采纳率: 100%
浏览 2928
已采纳

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

我有一个数组:

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

我无法改变数组的结构。我被传递了一个id 45,我想要得到数组中那个对象的id 'bar'。

如何在JavaScript或jQuery中做到这一点?

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

  • 写回答

28条回答 默认 最新

  • Memor.の 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).

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

报告相同问题?

悬赏问题

  • ¥15 luckysheet
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误