0

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.

Steve
  • 197
  • 7
  • 17
  • Does this answer your question? [Array of objects return object when condition matched](https://stackoverflow.com/questions/55491211/array-of-objects-return-object-when-condition-matched) – Anurag Srivastava Mar 06 '22 at 15:41

2 Answers2

3

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);
Anna
  • 259
  • 1
  • 6
1

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.

Thomas J.
  • 19
  • 2