How can I remove sub-objects?
[{
"id": "1",
"desc": "SOME PRODUCT",
"codigo": "CODE-28",
"codigoBarras": "2000000001",
"unidade": "PCT",
"price": "24.15",
"current_inventory": [{
"2kg": "5",
"5kg": "5",
"10kg": "5",
"20kg": "5",
"productId": "1"
}]
}]
[{
"id": "1",
"desc": "SOME PRODUCT",
"codigo": "CODE-28",
"codigoBarras": "2000000001",
"unidade": "PCT",
"price": "24.15",
"current_inventory_2kg": "5",
"current_inventory_5kg": "5",
"current_inventory_10kg": "5",
"current_inventory_20kg": "5",
}]
Use Object.entries
and reduce
will simplify.
const data = [ { id: "1", desc: "SOME PRODUCT", codigo: "CODE-28", codigoBarras: "2000000001", unidade: "PCT", price: "24.15", current_inventory: [ { "2kg": 5, "5kg": 5, "10kg": 5, "20kg": 5, productId: 1 } ] } ]; const [first] = data; const updated = Object.entries(first).reduce((acc, [key, value]) => { if (Array.isArray(value)) { value.forEach(item => Object.entries(item).forEach( ([cKey, cValue]) => (acc[`${key}_${cKey}`] = cValue) ) ); } else { acc[key] = value; } return acc; }, {}); console.log(updated);
Use Object.keys()
and a forEach
loop
var x =[ { "id": "1", "desc": "SOME PRODUCT", "codigo": "CODE-28", "codigoBarras": "2000000001", "unidade": "PCT", "price": "24.15", "current_inventory": [ { "2kg": "5", "5kg": "5", "10kg": "5", "20kg": "5", "productId": "1" } ] } ] x[0].current_inventory.forEach(e=>{ Object.keys(e).forEach(j=>{ x[0]['current_inventory_'+j]=e[j]; }) delete x[0].current_inventory }) console.log(x)
THANK YOU VERY MUCH!!!
Solved using the code below:
data is de object
estoqueFracionado is the sub-object
for (let [key, value] of Object.entries(data)) {
value.estoqueFracionado.forEach (e => {
Object.keys(e).forEach(j => {
value['estoqueFracionado_' + j] = e[j]
})
delete value.estoqueFracionado
})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.