I am trying to replace name, occupation and title for the following array of objects and capitalise each value. Some of the values can be null and if the value is null then replace null with "N/A". What would be the shortest/best way in es6 without all the if/else statements?
const array = [{
"id": 1,
"name": "sarah",
"title": "miss,
"occupation": "student"
}, {
"id": 2,
"name": null,
"title" : null,
"occupation": null,
}]
What I have so far:
const result = array.map((x) => {
if (x.name){
x.name = x.name.charAt(0).toUpperCase() + x.name.slice(1)
} else {
x.name = "N/A"
}
if (x.title){
x.title = x.title.charAt(0).toUpperCase() + x.title.slice(1)
} else {
x.title = "N/A"
}
if (x.occupation){
x.occupation = x.occupation.charAt(0).toUpperCase() + x.occupation.slice(1)
} else {
x.occupation = "N/A"
}
return x
});
Expected output:
const array = [{
"id": 1,
"name": "Sarah",
"title": "Miss,
"occupation": "Student"
}, {
"id": 2,
"name": "N/A",
"title" : "N/A",
"occupation": "N/A",
}]
Aucun commentaire:
Enregistrer un commentaire