javascript 如何在给定字典的情况下翻译Object?

bvn4nwqk  于 2023-04-04  发布在  Java
关注(0)|答案(1)|浏览(178)

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

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
}

但实际情况是,它只保存最新的选择,并覆盖其他所有内容,所以我最终在主对象中有一个对象。
但是为什么呢?我把对象赋值给翻译后的对象,这样它就应该把它添加到空对象中,而不是覆盖它

pqwbnv8z

pqwbnv8z1#

嗯... Stack Overflow的编辑器在“?”和“.”之间自动插入空格,这导致了一个错误。现在尝试一下。(现在只有在字典中总是有一个值的条目时才有效:否则会给予错误)。

将每一项拆分成键值对,翻译,重组

这里有一个方法来做到这一点:

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)

相关问题