js returns an object based on a property of an object array

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 returnreturn 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 idwhose property is equal to targetId. The parameter of the function objrepresents each element in the object array, and is used to obj.id === targetIdjudge whether the current element meets the condition. Finally, targetObjwhat is saved in the variable is the object that meets the condition.

Supongo que te gusta

Origin blog.csdn.net/klylove/article/details/130596949
Recomendado
Clasificación