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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作