Here is an example of JSON data:
[{
"address": "A-D-1",
"batch": [{
"batch_number": "B-123",
"cost": [{
"cost": "C1"
}]
}]
},
{
"address": "A-85-1",
"batch": [{
"batch_number": "B-6562",
"cost": [{
"cost": "C16464"
}]
}]
},
{
"address": "A-522-1",
"batch": [{
"batch_number": "B-4511",
"cost": [{
"cost": "C8745"
}]
}]
}]
I am looking to convert this JSON data into an array.
let data = JSON.parse('[{"address":"A-D-1","batch":[{"batch_number":"B-123","cost":[{"cost":"C1"}]}]},{"address":"A-85-1","batch":[{"batch_number":"B-6562","cost":[{"cost":"C16464"}]}]},{"address":"A-522-1","batch":[{"batch_number":"B-4511","cost":[{"cost":"C8745"}]}]}]');
for (let i = 0; i < data.length; i++) {
if (data[i].batch !== undefined && data[i].batch !== null && data[i].batch.length !== undefined && data[i].batch.length > 0) {
let batchLength = data[i].batch.length
let newObject = {}
let newArray = []
for (let j = 0; j < batchLength; j++) {
if (data[i].batch !== undefined && data[i].batch[j].cost !== null && data[i].batch[j].cost.length !== undefined && data[i].batch[j].cost.length > 0) {
let costLength = data[i].batch[j].cost.length
for (let k = 0; k < costLength; k++) {
newObject.location = data[i].address
newObject.batch.number = data[i].batch[j].batch_number ? data[i].batch[j].batch_number : ''
newObject.cogs = data[i].batch[j].cost[k].cost ? data[i].batch[j].cost[k].cost : ''
newArray.push(newObject)
}
}
}
}
}
The JSON data has been stored in the data
variable.
I have attempted to use the code above, but I keep getting the last index repeated.
Desired Output:
[
{
"address":"A-D-1",
"batch":{
"batch_number":"B-123"
},
"cost":"C1"
},
{
"address":"A-85-1",
"batch":{
"batch_number":"B-6562"
},
"cost":"C16464"
},
{
"address":"A-522-1",
"batch":{
"batch_number":"B-4511"
},
"cost":"C8745"
}
]
Any assistance would be appreciated.
Thank You.