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

Find a single value in array of objects in JavaScript

I’m a noob when it comes to JS and am trying to figure out how to return a single value instead of an object when using the .find() function.

Example:

var obj = [
    { name: 'Max', age: 23 },
    { name: 'John', age: 20 },
    { name: 'Caley', age: 18 }
];
 
var found = obj.find(e => e.name === 'John');
console.log(found);

This will output { name: 'John', age: 20 }

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

I want it to output John’s age (ie: 20) as a string.

What am I missing?

>Solution :

Simple add ?.age to your found variable.

var obj = [
    { name: 'Max', age: 23 },
    { name: 'John', age: 20 },
    { name: 'Caley', age: 18 }
];
 
var found = obj.find(e => e.name === 'John')?.age; // Using ?. incase value isnt found.
console.log(found);

You also mention you need it as a string, you can do achieve by wrapping the found var in the String function like so…

var obj = [
    { name: 'Max', age: 23 },
    { name: 'John', age: 20 },
    { name: 'Caley', age: 18 }
];
 
var found = String(obj.find(e => e.name === 'John')?.age);
console.log(found);
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