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.

1

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.