Home > Net >  Javascript: How to iterate through an array looking for an object value?
Javascript: How to iterate through an array looking for an object value?

Time:03-07

I have a js file that is just a an array with the name and type of person. I am trying to write a function in my other file to iterate through that array of objects and return just the object that matches a certain criteria. Here is my code.

person.js

export const persons_options = [
  { 
     name: 'Andrew',
     type: 'Athlete',
  },
  { 
     name: 'Paul',
     type: 'Worker',
  },
  { 
     name: 'Phil',
     type: 'Developer',
  },
 
]

utils.js

// params initialized already
person_type = params.subType
const name = persons_options.map((option) => {
    if(person_type === option.type){
        return option.name
    }
})

const person = name

The issue is I know map creates a new array so the output is ,,Phil. How would I just return one of the object names instead of all of them.

CodePudding user response:

find() will do the work

let persons_options = [
  { 
     name: 'Andrew',
     type: 'Athlete',
  },
  { 
     name: 'Paul',
     type: 'Worker',
  },
  { 
     name: 'Phil',
     type: 'Developer',
  },
 
]

let obj = persons_options.find(o => o.type === 'Developer');
//to return name
console.log("name",obj.name);

console.log(obj);

CodePudding user response:

You need to use the find function.

See here the list of functions that you can call on an array: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#instance_methods

filter might best suit your case if multiple results may be returned.

  • Related