如何翻译给定字典的对象?



我有一个通用名称的选择对象:

selections =  [
0: {division: 'division1', branch: 'branch1'}
1: {division: 'division2', branch: 'branch2'}
2: {division: 'division3', branch: 'branch3', department: 'department1'}
3: {division: 'division4', branch: 'branch4'}
]

我还为他们准备了一本字典:

translation = {
division: { division1: "Some Division", division2: "Some Other Division", division3: "Another Division", division4: "One More" }
branch: { branch1: "Br1", branch2: "Br2", branch3: "Br3", branch4: "Br4" }
department: { department1: "Dep1", department2: "Dep2", department3: "Dep3", department4: "Dep4" }
}

我试图通过创建一个新的空对象来转换单元,迭代每个选择并将转换后的对象分配给空对象:

let translatedSelections = {}; // new selections object
for (let selection of selections) {
let translatedSelection = {}; // empty selection object for each iteration
for (const [key, value] of Object.entries(selection) {
translatedSelection[key] = translation[key][value]; // set the translation 
}

translatedSelections = Object.assign(translatedSelections, translatedSelection); // assign the translation to the main object
}

但是发生的事情是它只保存了最新的选择,并覆盖了其他所有内容,所以我最终在主对象中只有一个对象。

但是为什么呢?我将对象赋值给转换后的对象所以它应该将其添加到空对象中,而不是覆盖它

嗯…Stack Overflow的编辑器会自动在"?"one_answers"!"这导致了一个错误。现在试试吧。(现在只有当字典中总是有对应该值的条目时,它才会工作,否则它将给出一个错误。)

将每个条目分解为键值对,翻译,重新组合

这里有一种方法:

const translatedSelections = selections.map(selection => {
const keyValuePairs = Object.entries(selection);
const translatedKeyValuePairs = keyValuePairs.map(
([key, value]) =>
([key, translation ?.[key] ?.[value]])
);
return Object.fromEntries(translatedKeyValuePairs)
})

selections = [{
division: 'division1',
branch: 'branch1'
},
{
division: 'division2',
branch: 'branch2'
},
{
division: 'division3',
branch: 'branch3',
department: 'department1'
},
{
division: 'division4',
branch: 'branch4'
}
]
translation = {
division: {
division1: "Some Division",
division2: "Some Other Division",
division3: "Another Division",
division4: "One More"
},
branch: {
branch1: "Br1",
branch2: "Br2",
branch3: "Br3",
branch4: "Br4"
},
department: {
department1: "Dep1",
department2: "Dep2",
department3: "Dep3",
department4: "Dep4"
}
}
const translatedSelections = selections.map(selection => {
const keyValuePairs = Object.entries(selection);
const translatedKeyValuePairs = keyValuePairs.map(
([key, value]) =>
([key, translation[key][value]])
);
return Object.fromEntries(translatedKeyValuePairs)
})
console.log(translatedSelections)

相关内容

  • 没有找到相关文章

最新更新