I have multidimensional JSON that I need to iterate and adapt to a typescript object formatted for my view.
{
"data": {
"id": "71",
"type": "quotations",
"attributes": {
"parts": {
"name supplier 1": [
{
"id": 1,
"part_number": "10-09800",
"title": "FALCON ACCELEROMETER G METER -5G TO +10G",
"supplier_id": 1
},
{
"id": 3,
"part_number": "1999",
"title": "Peça teste",
"supplier_id": 1
}
],
"name supplier 2": [
{
"id": 2,
"part_number": "10-09800",
"title": "FALCON ACCELEROMETER G METER -5G TO +10G",
"supplier_id": 2
}
]
}
}
}
}
How to iterate this JSON by separating items according to their respective suppliers.
private responseToQuotationSuppliers(response: Response): QuotationSupplier {
const collection = response.json().data.attributes['parts'];
const suppliers: QuotationSupplierPart[] = [];
const parts: Part[] = [];
for (const i in collection) {
for (const j in collection[i]) {
collection[key].forEach(item => {
let part = new Part(
item.id,
item.part_number,
item.tile,
item.supplier_id
)
parts.push(part);
})
}
let supplier = new QuotationSupplierPart(
key,
parts
)
suppliers.push(supplier);
}
return new QuotationSupplier(
suppliers,
response.json().data.id
)
}
I'm doing it that way, but all the suppliers are getting all the pieces.
Could someone give me a light to iterate this JSON in the correct way?
parts = []after you push parts onto the supplier. Otherwise, you keep reusing the same array for all suppliers, and tying the same parts array to all suppliers. Note, even after you add a parts array to a supplier, if you push more onto that array, the supplier will now have those parts, because you mutated the array. An even better solution would be to get a new parts array at the beginning of each loop iteration.consttolet, in your ‘const parts: Part[] = [];` line. That will allow you set it to a new array later. Then, right after thesuppliers.push(supplier);addparts = [];. This will give you a fresh array for your next supplier.collection[key]shouldn’t that becollection[i][j]?