从一个对象创建一个对象数组

时间:2018-05-15 08:42:33

标签: javascript functional-programming

我在功能性编程游戏中有点迷失。

我有一个这样的对象:

const answers = {1: 'first', 2:'second', 3:'third', 4:'fourth'}

我想将对象重塑为像这样的对象数组。

const arrayOfAnswers = [{1:'first'}, {2:'second'}, {3:'third'}, {4:'fourth'}]

达到此目标的简单解决方案是什么?

4 个答案:

答案 0 :(得分:6)

您可以使用销毁键/值进行映射。

var answers = { 1: 'first', 2: 'second', 3: 'third', 4: 'fourth' },
    array = Object.entries(answers).map(([k, v]) => ({ [k]: v }));
    
console.log(array);

答案 1 :(得分:1)

假设你的意思

answers = {1: "first", 2:"second" , 3:"third", 4:"fourth"};

使用Object.entriesmap

var output = Object.entries(answers).map( s => ({[s[0]]: s[1]}) )

答案 2 :(得分:0)

您可以使用迭代对象的键来完成它。我将给出一个ES5解决方案,假设:

  1. 其他人会给ES6解决方案。
  2. 您认为answers = {1: "first", 2: "second" , 3: "third", 4: "fourth"}
  3. var answers = {
      1: "first",
      2: "second",
      3: "third",
      4: "fourth"
    };
    var finalAnswers = [];
    var ansKeys = Object.keys(answers);
    for (var i = 0; i < ansKeys.length; i++) {
      obj = {};
      obj[ansKeys[i]] = answers[ansKeys[i]];
      finalAnswers.push(obj);
    }
    console.log(finalAnswers);

答案 3 :(得分:0)

您也可以使用Array.prototype.reduce方法。

const answers = {1: 'first', 2:'second', 3:'third', 4:'fourth'};

console.log(Object.entries(answers).reduce((acc, v) => acc.concat({[v[0]]: v[1]}), []));