es6中最好的方法是什么



我正在尝试替换以下对象数组的名称、职业和标题,并将每个值大写。一些值可以为null,如果该值为null;N/A";。如果没有所有if/else语句,es6中最短/最好的方法是什么?

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

到目前为止我所拥有的:

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

预期输出:

const array = [{
"id": 1,
"name": "Sarah",
"title": "Miss,
"occupation": "Student"
}, {
"id": 2,
"name": "N/A",
"title" : "N/A",
"occupation": "N/A",
}]

您只需创建一个函数即可完成重复工作

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)

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

这使用了ES8功能。

作为对象定义的一部分,您可以使任何字符串值更通用

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

您可以使用一个小函数来避免所有重复的代码:

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

然后,如果你可以在适当的位置修改数组,你就不需要创建一个新的重复数组:

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

或者,如果您想创建新阵列,而不是修改现有阵列:

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

或者,如果您想要,您甚至可以内联嵌入leadingUpper()函数:

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

注意:与提供的其他一些解决方案不同;"安全";其仅修改具体命名的属性nametitleoccupation。如果任何对象上碰巧有其他属性,它不会修改它们。我认为这是一种很好的防御性编码实践,如果其他开发人员将来在对象中添加一个不应该进行资本化处理的新属性,它就不会变得脆弱。

相关内容

最新更新