Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading