在 JavaScript 对象数组中按 id 查找对象 [英] Find object by id in an array of JavaScript objects

查看:53
本文介绍了在 JavaScript 对象数组中按 id 查找对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

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

我无法更改数组的结构.我被传递了 45 的 id,我想为数组中的那个对象获取 'bar'.

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.

如何在 JavaScript 或使用 jQuery 中执行此操作?

How do I do this in JavaScript or using jQuery?

推荐答案

使用find()方法:

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

来自 MDN:

find() 方法返回数组中的第一个值,如果数组中的元素满足提供的测试函数.否则返回 undefined.

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


如果你想找到它的index,使用findIndex():

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

来自 MDN:

findIndex() 方法返回数组中满足提供的测试函数的第一个元素的索引.否则返回-1.

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


如果您想获取匹配元素的数组,请使用 filter() 方法:

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

这将返回一个对象数组.如果您想获得一组 foo 属性,您可以使用 map() 方法:

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);


旁注:find()filter()箭头函数 不支持较旧的浏览器(如 IE),所以如果你想支持这些浏览器,你应该使用Babel(使用 polyfill).


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).

这篇关于在 JavaScript 对象数组中按 id 查找对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆