0

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 }

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

What am I missing?

0stone0
  • 34,288
  • 4
  • 39
  • 64

2 Answers2

2

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);
Levi Cole
  • 3,561
  • 1
  • 21
  • 36
0

.find function return you an object so you can just do something like this

var age = obj.find(e => e.name === "John").age
adevinwild
  • 278
  • 4
  • 8