将数组转换为具有小写键和句子大小写值的对象



转换的最佳方式是什么:

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

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

PS:这里,对象的键应该是数组的小写元素,而键的值应该是数组元素的句子大小写。

下面的代码片段应该会有所帮助。在这里,我们有一种方法,将每个字符串中的值大写,然后在每个大写字母之前引入一个空格,方法是在这一点上拆分,然后用空格连接。在数组的forEach循环中使用它可以构造所需的对象。

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(' ');
}

您可以在数组上reduce并生成一个新对象。在这里,我使用了一个正则表达式来match字符串。

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);

最新更新