You can use Array.prototype.find()
the method to return objects based on a property of an array of objects. This method receives a function as a parameter, in which you can access each element of the object array, and return
return the qualified object through the statement. The sample code is as follows:
const objArr = [
{
id: 1, name: 'apple' },
{
id: 2, name: 'banana' },
{
id: 3, name: 'orange' }
];
const targetId = 2;
const targetObj = objArr.find(obj => obj.id === targetId);
console.log(targetObj);
// 输出: { id: 2, name: 'banana' }
In the above example, we first define an array containing objects objArr
, and then we call Array.prototype.find()
the method to find objects id
whose property is equal to targetId
. The parameter of the function obj
represents each element in the object array, and is used to obj.id === targetId
judge whether the current element meets the condition. Finally, targetObj
what is saved in the variable is the object that meets the condition.