Very new to programming and I'm doing some online tutorials. Hoping someone would be kind enough to help me.
What I have is the following JSON data from an API response. strOption[i] and strPrice[i] will go up to 10 even if there are no values so I want to get rid of those.
Formatting isn't perfect but I'm sure you get the picture.
cars {
"car": [
0 : {
"carId": "17209",
"strModel": "Discovery",
"strYear": "2022",
"strOption1": "S",
"strOption2": "R-D S",
"strOption3": "R-D HSE",
"strOption4": "",
"strPrice1": "68,600",
"strPrice2": "71,100",
"strPrice3": "85,400",
"strPrice4": ""
}
1 : {
"carId": "11349",
"strModel": "Sport",
"strYear": "2022",
"strOption1": "SE",
"strOption2": "HSE",
"strOption3": "HST",
"strOption4": "",
"strPrice1": "82,200",
"strPrice2": "93,700",
"strPrice3": "98,100",
"strPrice4": ""
}
]
}
What I want to do is loop through the data and end up with this.
*Note strOption1 must pair with strPrice1 so I can access strOptions[0] with strPrices[0], etc.
cars {
"car": [
0 : {
"carId": "17209",
"strModel": "Discovery",
"strYear": "2022",
"strOptions": ["S", "R-D S", "R-D HSE"],
"strPrices": ["68,600", "71,100", "85,400"]
}
1 : {
"carId": "11349",
"strModel": "Sport",
"strYear": "2022",
"strOptions": ["SE", "HSE", "HST"],
"strPrices": ["82,200", "93,700", "98,100"]
}
]
}
CodePudding user response:
You can use combination of Object.prototype.keys
, Array.prototype.forEach()
and String.prototype.startsWith()
to get the functionality you want.
const cars = {
"car": [
{
"carId": "17209",
"strModel": "Discovery",
"strYear": "2022",
"strOption1": "S",
"strOption2": "R-D S",
"strOption3": "R-D HSE",
"strOption4": "",
"strPrice1": "68,600",
"strPrice2": "71,100",
"strPrice3": "85,400",
"strPrice4": ""
},
{
"carId": "11349",
"strModel": "Sport",
"strYear": "2022",
"strOption1": "SE",
"strOption2": "HSE",
"strOption3": "HST",
"strOption4": "",
"strPrice1": "82,200",
"strPrice2": "93,700",
"strPrice3": "98,100",
"strPrice4": ""
}
]
}
const result = cars.car.map(el => {
let details = { // default object
"strOptions": [],
"strPrices": []
}
Object.keys(el).forEach(key => {
if(key.startsWith('strOption')){
if(el[key]) // prevent ""
details.strOptions.push(el[key])
} else if(key.startsWith('strPrice')) {
if(el[key]) // prevent ""
details.strPrices.push(el[key])
} else {
details[key]=el[key]
}
})
return details
})
console.log(result)