Tengo una variedad de objetos como a continuación:
checklist= [ { "participantId": 13, "rankStatus": "participated", "rank": 3, "comment": "my comment", "horse_name": "test232 fdfgdg", "country": "Afghanistan", "life_number": null }, { "participantId": 12, "rankStatus": "eliminated", "comment": null, "horse_name": "test horse", "country": "Algeria", "life_number": "234234" }, { "participantId": 11, "rankStatus": null, "rank": null, "comment": null, "horse_name": "tesdfs", "country": "Afghanistan", "life_number": null }, { "participantId": 10, "rankStatus": null, "comment": null, "horse_name": "nam horse", "country": "India", "life_number": "fh345" } ]; En la matriz de objetos anterior, necesito agregar rank=0 a los objetos donde el rank no está presente.
Intenté como se muestra a continuación, pero no pude encontrar la forma correcta de hacerlo.
checklist.filter(x => !x.hasOwnProperty('rank') ).map(x => x.rank == 0);¿Cuál es la forma correcta de hacer esto? Por favor ayuda y guía. Gracias
Yo solo haría:
checklist.map(item => ({ rank: 0, ...item })) Dado que distribuye item tras rango, si tiene un rank , el 0 se sobrescribirá, si no existe, terminará con 0 para el rango.
Si el rendimiento es una preocupación, probablemente sea más eficiente hacer:
checklist.forEach((item) => item.rank = item.rank || 0);