添加连续字母作为对象键

时间:2018-09-13 15:44:06

标签: javascript arrays function object

我想创建具有给定结构的对象:

speechToText.py

我有一个数组,其中包含必要的信息以填充该对象并使用$ python speechToText.py -v ['speechToText.py'] $ python speechToText.py -x ['speechToText.py', '-x'] $ python speechToText.py -v -v ['speechToText.py'] $ python speechToText.py -v -v -x ['speechToText.py', '-x'] 创建它。

const questions = [
  {
    id: '1',
    instruction: 'Question1',
    options: {
      'a': 'SomeText1',
      'b': 'SomeText2',
      'c': 'SomeText3'
    },
    correct: ['c']
  },
  {
    id: '2',
    instruction: 'Question2',
    options: {
      'a': 'SomeText1',
      'b': 'SomeText2',
      'c': 'SomeText3',
      'd': 'SomeText4'
    },
    correct: ['a']
  },
  {
    id: '3',
    instruction: 'Question3,
    options: {
      'a': 'SomeText1',
      'b': 'SomeText2'
    },
    correct: ['b']
  }
]

我只有.map()键有问题。如您所见,我想将字母作为键,具体取决于问题的答案数量。 当我使用const questions = [ 'Question1', 'Question2', 'Question3' ] const answers = [ 'Answer1', 'Answer2', 'Answer3' ] const options = [ [ 'Option1', 'Option2', 'Option3' ], [ 'Option4', 'Option5', 'Option6' ], [ 'Option7', 'Option8', 'Option9' ] ] function toJson() const alphabet = ['a', 'b', 'c', 'd', 'e']; const json = questions.map((question, index) => ( { id: index + 1, instruction: question, options: Object.assign({}, options[index]), correct: answers[index] } )) } 时,此函数为我提供数字作为键,而且我不知道如何用options数组中的字母替换它们。

编辑:

因此,所需对象中的Object.assign()键的解决方案是:

alphabet

现在,我可以创建具有连续字母并分配了答案的对象。

3 个答案:

答案 0 :(得分:2)

我建议使用类似zipobjectFromPairs的东西(都是30secondsofcode的片段,这是我维护的项目/网站)。从网站上:

zip

  

创建一个元素数组,根据原始数组中的位置进行分组。

     

使用Math.max.apply()获取参数中最长的数组。创建一个具有该长度的数组作为返回值,并将Array.from()与map函数一起使用以创建分组元素的数组。如果参数数组的长度不同,则在找不到值的地方使用undefined

objectFromPairs

  

根据给定的键值对创建对象。

     

使用Array.reduce()创建和组合键值对。

我唯一要做的额外步骤是将每个压缩数组修剪为length的{​​{1}}。

options[index]

答案 1 :(得分:2)

options[index]返回一个数组。它包含按索引的值。通过将其传递到Object.assign,您可以按数组索引将所有值作为字符串添加:"0""1"等。

如果我们首先将数组map放入{ "a": option }的列表中,并将结果散布到Object.assign调用中,则可以将这些索引更改为所需的字母:< / p>

const questions = 
[ 'Question1',
  'Question2',
  'Question3'
]

const answers = 
[ 
 'Answer1',
 'Answer2',
 'Answer3'
]

const options = [
   [ 'Option1', 'Option2', 'Option3' ],
   [ 'Option4', 'Option5', 'Option6' ],
   [ 'Option7', 'Option8', 'Option9' ]
 ]

function toJson() {
  const alphabet = ['a', 'b', 'c', 'd', 'e'];
  const json = questions.map((question, index) => (
    {
      id: index + 1,
      instruction: question,
      options: Object.assign(
        {}, 
        ...options[index].map((a, i) => ({ [alphabet[i]]: a }))
      ),
      correct: answers[index]
    }
  ));
  
  return json;
}

console.log(toJson());

答案 2 :(得分:0)

编辑:

因此所需对象中选项键的解决方案是:

options: Object.assign(
        {}, 
        ...options[index].map((a, i) => ({ [alphabet[i]]: a }))
      ),