Home > database >  What is the best way in es6
What is the best way in es6

Time:09-23

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",
}]

CodePudding user response:

You can just create a function which does the repetitive work

const array = [{
  "id": 1,
  "name": "sarah",
  "title": "miss",
  "occupation": "student"
}, {
  "id": 2,
  "name": null,
  "title": null,
  "occupation": null,
}]

function assignValue(a) {
  return a ? a.charAt(0).toUpperCase()   a.slice(1) : "N/A"
}
const newData = array.map(a => {
  return {
    id: a.id,
    name: assignValue(a.name),
    title: assignValue(a.title),
    occupation: assignValue(a.occupation)
  }
});
console.log(newData)

CodePudding user response:

const output = array.map(object => {
    return Object.fromEntries(Object.entries(object).map(entry => {
        if(entry[0] == "id") return [entry[0], entry[1]]
        const newValue = entry[1] ? entry[1].charAt(0).toUpperCase()   entry[1].slice(1) : "N/A"
        return [entry[0], newValue]
   }));
});

This uses ES8 features.

CodePudding user response:

You can make it more generic for any string value as part of your object definition

const array = [{
    id: 1,
    name: "first middle last",
    title: "miss",
    occupation: "software engineer"
  },
  {
    id: 2,
    name: null,
    title: null,
    occupation: "student"
  }
];

capitalize = (str) => {
  return str
    .toLowerCase()
    .split(" ")
    .map((wrd) => {
      return wrd[0].toUpperCase()   wrd.slice(1);
    })
    .join(" ");
};

const transformArr = array.map((el) => {
  for (const key of Object.keys(el)) {
    if (!el[key]) {
      el[key] = "N/A";
    } else if (typeof el[key] === "string") {
      el[key] = capitalize(el[key]);
    }
  }
  return el;
});

console.log(transformArr);

CodePudding user response:

You can use a small little function to avoid all the duplicate code:

function leadingUpper(str) {
    if (str) {
        return str.charAt(0).toUpperCase()   str.slice(1);
    } else {
        return "N/A";
    }
}

Then, if you can modify the array in place, you won't need to create a new duplicate array:

for (const obj of array) {
    for (const field of ["name", "title", "occupation"]) {
        array[field] = leadingUpper(array[field]);
    }
}

Or, if you want to create the new array, rather than modifying the existing one:

const result = array.map(obj => {
    for (const field of ["name", "title", "occupation"]) {
        array[field] = leadingUpper(array[field]);
    }
});

Or, you could even embed the leadingUpper() function inline if you want:

const result = array.map(obj => {
    for (const field of ["name", "title", "occupation"]) {
        const str = array[field];
        array[field] = str ? str.charAt(0).toUpperCase()   str.slice(1) : "N/A";
    }
});

Note: Unlike some of the other solutions offered, this is "safe" in that it only modifies the specifically named properties name, title and occupation. If there happen to be other properties on any of the objects, it won't modify them. I consider this a good, defensive coding practice that isn't brittle if some other developer adds a new property to the object in the future that isn't supposed to get the capitalization treatment.

  • Related