1

What is the best way to convert:

['firstName', 'lastName', 'recordSource']

to

{firstname: 'First Name', lastname: 'Last Name', recordsource: 'Record Source'}

PS: Here, the key of the object should be a lowercased element of the array whereas the value of the key should be the Sentence Case of the array element.

ajay
  • 328
  • 1
  • 5
  • 17
  • Does this answer your question? [Variable name as a string in Javascript](https://stackoverflow.com/questions/4602141/variable-name-as-a-string-in-javascript) – Wais Kamal Jun 18 '21 at 08:43
  • 1
    Did you mean `['firstName', 'lastName', 'recordSource']`? – Andy Jun 18 '21 at 08:44
  • @ajay - There seems to be an inconsistency in the question. Could you clarify whether `lastname: 'LastName'` is correct, or if it should be `lastname: 'Last Name'`? – Bladeski Jun 18 '21 at 08:45
  • @Bladeski it should be like this: ```lastname: 'Last Name'``` – ajay Jun 18 '21 at 08:47

2 Answers2

1

The following code snippet should help. Here we have a method that capitalises the value in each string and then introduces a space before each capital letter by splitting at this point and then joining with a space. Using this in a forEach loop on the array allows us to construct the required object.

const data = ['firstName', 'lastName', 'recordSource'];
const dataObject = {};

data.forEach(item => {
  dataObject[item.toLowerCase()] = stringToCapitalised(item);
});
console.log(dataObject);

function stringToCapitalised(value) {
  let capitalised = value[0].toUpperCase() + value.substring(1);
  return capitalised.split(/(?=[A-Z])/).join(' ');
}
Bladeski
  • 371
  • 2
  • 10
1

You can reduce over the array and produce a new object. Here I've used a regular expression to match the strings.

const arr = ['firstName', 'lastName', 'recordSource'];

// A regex to separate out the first and last words
const regex = /([a-z]+)([A-Z][a-z]+)/

// Iterate over the array
const result = arr.reduce((acc, c) => {

  // Match the first and last words using the regex
  const [, first, last] = c.match(regex);

  // Create the key and value
  const key = c.toLowerCase();
  const value = `${first[0].toUpperCase()}${first.substr(1)} ${last}`;
  acc[key] = value;

  // Return the accumulator for the next iteration
  return acc;
}, {});

console.log(result);
Andy
  • 61,948
  • 13
  • 68
  • 95
  • Nice work! I like the approach. It works fine for the limited examples provided, but if there are cases where the input has more than two words (e.g. `NationalInsuranceNumber`) it provides the object value as only the first two words. I know this use case isn't specified in the question, so may not be an issue, but it is worth noting. – Bladeski Jun 18 '21 at 09:32
  • Thanks, mate. I upvoted your answer because it looked cleaner. Thanks for pointing out the issue, – Andy Jun 18 '21 at 09:34