Creating an array from another array

Asked

Viewed 912 times

3

var contatos = [
  {
    nome: 'Alex Silva Souza',
    endereco: 'Travessa 1, casa 233',
    tel: '2235-3514',
    id:1123,
    email: '****',
  },
  {
    nome: 'Beatriz Santana Pinto',
    endereco: 'Rua cardoso de moraes, casa 21',
    tel: '3448-3514',
    id:1124,
    email: '[email protected]'
  },
  {
    nome: 'Felippe Roger Teles',
    endereco: 'Rua Ana teles, casa 107',
    tel: '2556-1818',
    id:1125,
    email: '****'
  },
  {
    nome: 'Rogerio Machado da Silva',
    endereco: 'Rua Baronesa, 231 ap101',
    tel: '98337-3317',
    id:1126,
    email: '[email protected]'
  },
];


var identificacao = []

My intention is to place only the name and id properties inside the identification array. It would look like this :

var identificacao = [
  {
    nome: 'Alex Silva Souza',
    id:1123,
  },
  {
    nome: 'Beatriz Santana Pinto',
    id:1124,
  }
];

But what I’m doing returns this to me:

var identificacao = ["Alex Silva Souza", 1123, "Beatriz Santana Pinto", 1124, "Felippe Roger Teles", 1125, "Rogerio Machado da Silva", 1126]
  • These emails are real?

  • no kk, no data is real.

  • Look, one of them actually exists... http://omtaram.com/rogerioemonyke

  • lol ... But surely the data as address and name does not match the owner of the email, all items were invented by me.

1 answer

2


You must use the .map to map from one object to another.

var subselecao = contatos.map(function(contacto) {
  return {
    nome: contacto.nome,
    id: contacto.id
  };
});

An example would be like this:

var contatos = [{
    nome: 'Alex Silva Souza',
    endereco: 'Travessa 1, casa 233',
    tel: '2235-3514',
    id: 1123,
    email: '****',
  },
  {
    nome: 'Beatriz Santana Pinto',
    endereco: 'Rua cardoso de moraes, casa 21',
    tel: '3448-3514',
    id: 1124,
    email: '[email protected]'
  },
  {
    nome: 'Felippe Roger Teles',
    endereco: 'Rua Ana teles, casa 107',
    tel: '2556-1818',
    id: 1125,
    email: '****'
  },
  {
    nome: 'Rogerio Machado da Silva',
    endereco: 'Rua Baronesa, 231 ap101',
    tel: '98337-3317',
    id: 1126,
    email: '[email protected]'
  },
];

var subselecao = contatos.map(function(contacto) {
  return {
    nome: contacto.nome,
    id: contacto.id
  };
});

console.log(subselecao);

In modern browsers could be:

const subselecao = contatos.map(({nome, id}) => ({nome, id}));
  • 1

    Thank you very much. Look what I was doing: contacts.map( e => id.push(e. name, e.id));

  • @mtAlves therefore, the map is made for these cases. I am glad to have helped :)

Browser other questions tagged

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