我想根据语言使用JavaScript更改对象department_descr
:
var data = {
"language": "EN",
"contacts": [
{
"department_descr": {
"en": "Management",
"fr": "Gestion"
}
}
]
};
输出:
{
"language": "EN",
"contacts": [
{
"department_descr": "Management"
}
]
}
答案 0 :(得分:2)
首先,您的示例对象格式错误,这将导致语法错误。更改为此:
var data = {
"language": "EN",
"contacts": [
{
"department_descr": {
"en": "Management",
"fr": "Gestion"
}
}
]
}
第二,在这种情况下,不建议更改对象。您应该使用所需的模型创建一个新对象:
var desc = data.contacts[0].department_descr[data.language.toLowerCase()];
var newData = Object.assign({}, data, { contacts: [ { department_descr: desc } ] })
答案 1 :(得分:0)
这是一个将像这样的对象作为参数并根据language属性设置描述的函数。
从技术上讲,它返回一个 new 对象,而不是对现有对象进行突变,但这是绝大多数情况下您想要的。
function setDescription(srcObject){
let language = srcObject.language.toLowerCase();
let outputObj = Object.assign({}, srcObject);
outputObj.contacts = srcObject.contacts.map((contact) =>{
let newDescription = contact.department_descr[language];
contact.department_descr = newDescription;
return contact;
});
return outputObj;
}
这将适用于任意长度的contacts数组。它有某些假设。
答案 2 :(得分:0)
演示:
var data = {
"language": "EN",
"contacts": [
{
"department_descr": {
"en": "Management",
"fr": "Gestion"
}
}
]
};
for (var i of data.contacts) {
if(Object.keys(i.department_descr).includes(data.language.toLowerCase()) === true) {
i.department_descr = i.department_descr[data.language.toLowerCase()];
}
}
console.log(data);