Soy muy nuevo en programación y estoy haciendo algunos tutoriales en línea. Esperando que alguien sea tan amable de ayudarme.
Lo que tengo son los siguientes datos JSON de una respuesta API. strOption[i] y strPrice[i] subirán a 10 incluso si no hay valores, así que quiero deshacerme de ellos.
El formato no es perfecto, pero estoy seguro de que te haces una idea.
cars { "car": [ 0 : { "carId": "17209", "strModel": "Discovery", "strYear": "2022", "strOption1": "S", "strOption2": "RD S", "strOption3": "RD 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": "" } ] } Lo que quiero hacer es recorrer los datos y terminar con esto.
*Tenga en cuenta que strOption1 debe emparejarse con strPrice1 para que pueda acceder a strOptions[0] con strPrices[0], etc.
cars { "car": [ 0 : { "carId": "17209", "strModel": "Discovery", "strYear": "2022", "strOptions": ["S", "RD S", "RD 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"] } ] }Puede usar una combinación de Object.prototype.keys , Array.prototype.forEach() y String.prototype.startsWith() para obtener la funcionalidad que desea.
const cars = { "car": [ { "carId": "17209", "strModel": "Discovery", "strYear": "2022", "strOption1": "S", "strOption2": "RD S", "strOption3": "RD 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)