如何根据对象中的键值对将数组映射到新数组?

时间:2018-02-22 09:37:10

标签: javascript arrays ecmascript-6

我正在编写一个可以测试的脚本。答案是口头的,每个词对应于1到5的特定数字值。

我创建了一个记录这些对应关系的对象:

const answerValues = {
    "Consistently": 5,
    "Often": 4,
    "Sometimes": 3,
    "Rarely": 2,
    "Never": 1
  }

答案在一系列数组中给出:

const answers = [
  ["Consistently, "Often", "Sometimes", "Rarely", "Never"],
  ["Often, "Sometimes", "Consistently", "Never", "Rarely"],
  ["Sometimes, "Rarely", "Consistently", "Rarely", "Often"]
]

我需要做的是将原始answers映射到一个新的数组,而不是像这样:

const answerResults = [
  [5, 4, 3, 2, 1],
  [4, 3, 5, 1, 2],
  [3, 2, 5, 1, 4]
]

我似乎无法让这个工作;任何帮助将不胜感激。

PS如果需要,我可以将answers数组更改为一个对象,如果这样可以使这更容易。

3 个答案:

答案 0 :(得分:3)

使用map

var output = answers.map( s => s.map( t => answerValues[t] ) )

<强>演示

&#13;
&#13;
var answerValues = {
  "Consistently": 5,
  "Often": 4,
  "Sometimes": 3,
  "Rarely": 2,
  "Never": 1
};
var answers = [
  ["Consistently", "Often", "Sometimes", "Rarely", "Never"],
  ["Often", "Sometimes", "Consistently", "Never", "Rarely"],
  ["Sometimes", "Rarely", "Consistently", "Rarely", "Often"]
];
var output = answers.map(s => s.map(t => answerValues[t]));
console.log(output);
&#13;
&#13;
&#13;

<强>解释

- use `map` to iterate `answers`,
-   use `map` for each `s` in `answers` and iterate the values
-     *replace* each value `t` with its `answerValues[t]`

答案 1 :(得分:2)

您可以使用内部数组的对象值映射外部数组。

&#13;
&#13;
const
    answerValues = { Consistently: 5, Often: 4, Sometimes: 3, Rarely: 2, Never: 1 },
    answers = [["Consistently", "Often", "Sometimes", "Rarely", "Never"],["Often", "Sometimes", "Consistently", "Never", "Rarely"], ["Sometimes", "Rarely", "Consistently", "Rarely", "Often"]],
    result = answers.map(a => a.map(k => answerValues[k]));

console.log(result);
&#13;
&#13;
&#13;

答案 2 :(得分:1)

简单使用嵌套映射,然后使用answerValues映射返回响应

&#13;
&#13;
const answers = [
  ["Consistently", "Often", "Sometimes", "Rarely", "Never"],
  ["Often", "Sometimes", "Consistently", "Never", "Rarely"],
  ["Sometimes", "Rarely", "Consistently", "Rarely", "Often"]
]

const answerValues = {
    "Consistently": 5,
    "Often": 4,
    "Sometimes": 3,
    "Rarely": 2,
    "Never": 1
}

const res = answers.map(answer => {
    return answer.map(resp => answerValues[resp]);
})
console.log(res)
&#13;
&#13;
&#13;