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

0

Hello, the server is returning me the following json

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

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

I need the client data not to be in a second json but in a field ex clienteNome: '' within this.itens this is just a generic example.

    
asked by anonymous 24.06.2018 / 23:55

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

Result:

{
  "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 the entries automatically. But in this case you will not be able to set the key name to clienteNome etc., unless you use multiple if s 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 parent 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 ES6 spread operator ( 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);
    
25.06.2018 / 00:10