How to transform an Array of Objects into a Simple Array? Javascript

2

I would like to know how I can transform an Object Array into a Simple Array only with a certain value.

I have this:

const names = [
  {id:0, name:"Jean"}, 
  {id:2, name:"Ricardo"}, 
  {id:4, name:"Letiiicia"}, 
  {id:5, name:"Dai"}, 
  {id:7, name:"Tamy"}, 
  {id:10, name:"Abeu"}, 

I wanted to return this to:

const names /*ou um novo array, não sei*/ = ['Jean','Ricardo','Leticia','Dai','Tamy','Abeu']

A new array only with names . Could someone help me?

    
asked by anonymous 03.03.2018 / 16:55

3 answers

5

The simplest is to use the % w / Array , which was precisely for this type of situations that was created. This allows you to get a new array based on a transformation of the current array.

In your case it would be something like:

names = persons.map(function(person){
    return person.name;
});

Where map would be the array of objects it had initially. The persons will call the function passed to each element of the array, and construct a new one with the returns obtained for each element.

With Arrow Functions gets even more straightforward, simple and easy to read:

names = persons.map(person => person.name);

We can read as follows: map is mapped with each persons being person .

See it working:

const persons = [
  {id:0, name:"Jean"}, 
  {id:2, name:"Ricardo"}, 
  {id:4, name:"Letiiicia"}, 
  {id:5, name:"Dai"}, 
  {id:7, name:"Tamy"}, 
  {id:10, name:"Abeu"}
];
  
const names = persons.map(person => person.name);
console.log(names);
    
03.03.2018 / 21:32
2

One way to do this is as follows:

var novoArray = []

for (i = 0; i < names.length; i++) {
   novoArray.push(names[i].name);      
}
    
03.03.2018 / 17:08
2

You can do this:

function myFunction(){

const obj = [
  {id:0, name:"Jean"}, 
  {id:2, name:"Ricardo"}, 
  {id:4, name:"Letiiicia"}, 
  {id:5, name:"Dai"}, 
  {id:7, name:"Tamy"}, 
  {id:10, name:"Abeu"}]

const names = obj.map(function(item) {
  return item['name'];
});

alert(names);
}
    
03.03.2018 / 17:14