我有多个实体,它们具有相同的结构(" entityId"和" name"),如下所示:
性别
"gender" : {
genderId: 1,
name: "someValue"
}
EducationLevel
"educationLevel" : {
educationLevelId: 1,
name: "someValue"
}
ProfessionalTitle
"professionalTitle" : {
professionalTitleId: 1,
name: "someValue"
}
我写了这个函数来获得一个通用的JSON但当然是错的。如何设置"字段+ Id"是否正确?
我的功能
function getGenericJson(field, nameValue, idValue){
var idName = field + "Id";
var fieldJson = {
name: nameValue,
field+"Id": idValue
}
return fieldJson;
}
输入示例
getGenericJson("gender", "someValue", 1);
答案 0 :(得分:2)
在ES6中,您可以这样写:
function getGenericJson(field, nameValue, idValue){
return {
name: nameValue,
[field+"Id"]: idValue
}
}
在ES5中,你会这样写:
function getGenericJson(field, nameValue, idValue){
var fieldJson = {
name: nameValue
};
fieldJson[field + "Id"] = idValue;
return fieldJson;
}
答案 1 :(得分:0)
尝试用括号括起它,如下所示:
var fieldJson = {
...,
[ field + "Id" ]: idValue
}
答案 2 :(得分:0)
<强>样本强>
ES5:
function getGenericJson(field, nameValue, idValue) {
var fieldJson = {};
fieldJson.name = nameValue;
fieldJson[field+"Id"] = idValue;
return fieldJson;
};
console.log(getGenericJson("gender", "someValue", 1));
ES6使用反引号(模板文字):
function getGenericJson(field, nameValue, idValue) {
let fieldJson = {};
let fieldName = `${field}ID`;
fieldJson.name = nameValue;
fieldJson[fieldName] = idValue;
return fieldJson;
};
console.log(getGenericJson("gender", "someValue", 1));