How to pass items from an [Object Object] to the parent json

Asked

Viewed 98 times

0

Hello the server is returning me the following json

this.itens  = { 
   id: '',
   data: '',
   hora: '',

   cliente:{
   nome: '',
   cpf: ''
   }
}

i need the customer data not to stay in a second json but in an ex field clienteNome: '' within this.items this is just a generic example.

  • And the Commission?.......

  • fixed is a customer field

  • yes, but you just want to take the name? And Cpf?

  • i want to get qlqr given is just a generic example

1 answer

1


You can create new entries in the first level of the object and delete the key cliente:

this.itens  = { 
   id: '1',
   data: '24/06/2018',
   hora: '19:03:00',

   cliente:{
   nome: 'Fulano de Tal',
   cpf: '123456789-01'
   }
}

itens['clienteNome'] = itens.cliente.nome; // cria nova chame e atribui o nome
itens['clienteCpf'] = itens.cliente.cpf; // cria nova chave e atribui o CPF

delete itens['cliente']; // apagar a chave "cliente" do objeto

console.log(itens);

Upshot:

{
  "id": "1",
  "data": "24/06/2018",
  "hora": "19:03:00",
  "clienteNome": "Fulano de Tal",
  "clienteCpf": "123456789-01"
}

Or you can iterate the object using for...in to create entries automatically. Only in this case you will not be able to set the key name as clienteNome etc., unless you use several ifs within the loop to give different names according to the given:

this.itens  = { 
   id: '1',
   data: '24/06/2018',
   hora: '19:03:00',

   cliente:{
   nome: 'Fulano de Tal',
   cpf: '123456789-01'
   }
}

for(var item in itens.cliente){
   itens[item] = itens.cliente[item];
}

delete itens['cliente'];

console.log(itens);

Another way is to merge the nested object cliente with the father itens:

this.itens  = { 
   id: '1',
   data: '24/06/2018',
   hora: '19:03:00',

   cliente:{
   nome: 'Fulano de Tal',
   cpf: '123456789-01'
   }
}

Object.assign(itens, itens.cliente);
delete itens['cliente'];

console.log(itens);

Or you can use the spread operator of ES6 (not supported by Microsoft browsers):

this.itens  = { 
   id: '1',
   data: '24/06/2018',
   hora: '19:03:00',

   cliente:{
   nome: 'Fulano de Tal',
   cpf: '123456789-01'
   }
}

itens = {...itens, ...itens.cliente};
delete itens['cliente'];

console.log(itens);

Browser other questions tagged

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