Return only an attribute of an object?

Asked

Viewed 63 times

1

I would like to know how to get only one object attribute ...

const person = [
  { name: 'Jane', age: 55 },
  { name: 'Rafael', age: 23 },
  { name: 'Carolina', age: 19 },
  { name: 'Bob', age: 47 },
  { name: 'Julia', age: 62 },
  { name: 'Joy', age: 43 }
];

const biggestNames = person.filter(person => person.name.length >= 5);
console.log(biggestNames);

So in this way, I will return the obj’s with the biggest names according to the argument that was passed (person.name.length >= 5), but I would like it to return only the value of the attribute name of my obj, and not the complete obj ({ name: x, age: x }) in you...

Thanks ...

1 answer

5

As well as the method filter there is also a method called map that you can invoke in an array to generate a new array. In this case, the map produces an array with the value returned from your callback, so simply return the name of the person in that callback:

const persons = [
  { name: 'Jane', age: 55 },
  { name: 'Rafael', age: 23 },
  { name: 'Carolina', age: 19 },
  { name: 'Bob', age: 47 },
  { name: 'Julia', age: 62 },
  { name: 'Joy', age: 43 }
];

const biggestNames = persons
  .filter(person => person.name.length >= 5)
  .map(person => person.name);
  
console.log(biggestNames);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.