【问题标题】:How can you map an array to a new array based on the key-value pairs in an object?如何根据对象中的键值对将数组映射到新数组?
【发布时间】:2018-02-22 18:29:31
【问题描述】:

我正在编写一个可以为测试评分的脚本。答案是口头的,每个单词对应一个从 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 数组更改为一个对象,如果这样会更容易。

【问题讨论】:

    标签: javascript arrays ecmascript-6


    【解决方案1】:

    使用map

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

    演示

    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);

    说明

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

    【讨论】:

      【解决方案2】:

      您可以将外部数组与内部数组的对象的值进行映射。

      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);

      【讨论】:

        【解决方案3】:

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

        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)

        【讨论】:

          猜你喜欢
          • 2021-04-20
          • 2019-09-25
          • 2019-04-28
          • 2012-01-11
          • 2022-12-19
          • 2018-03-10
          • 1970-01-01
          • 2020-07-22
          • 1970-01-01
          相关资源
          最近更新 更多