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