How to transform an Object Array into a Simple Array? Javascript

Asked

Viewed 1,407 times

1

I wanted to know how I can transform an Object Array to a Simple Array with only a certain vaor..

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 the names. Someone could help me ?

3 answers

4


The simplest is to use the function map array, which was precisely for this type of situations that was created. This allows you to obtain a new array based on a current array transformation.

In your case it would be something like:

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

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

With Arrow Functions is even more direct, simple and easy to read:

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

Which we can read as follows: persons is mapped and each person becomes person.name.

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

  • Thank you very much, Isac <3

2

One way to do it is this:

var novoArray = []

for (i = 0; i < names.length; i++) {
   novoArray.push(names[i].name);      
}
  • Thanks Paulo I got it!!

2

You can do it:

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);
}
  • Thank you Fernando!!

Browser other questions tagged

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