-3

I am a bit lost in my functional programming game.

I have an object like this:

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

I would like to reshape the object into an array of objects like this.

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

What would be an easy solution to reach this?

MokumJ
  • 181
  • 2
  • 9

4 Answers4

6

You could map with a destruction for key/value.

var answers = { 1: 'first', 2: 'second', 3: 'third', 4: 'fourth' },
    array = Object.entries(answers).map(([k, v]) => ({ [k]: v }));
    
console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • It's a great answer but the result type (asked by OP) is so strange that it begs the question how one would use such data... – Mulan May 15 '18 at 16:19
1

Assuming you meant

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

Use Object.entries and map

var output = Object.entries(answers).map( s => ({[s[0]]: s[1]}) )
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

You can do it using iterating the object's keys. I'll give an ES5 solution, assuming:

  1. Others would be giving ES6 solution.
  2. You assumed answers = {1: "first", 2: "second" , 3: "third", 4: "fourth"}

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);
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

You can also use Array.prototype.reduce method.

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

console.log(Object.entries(answers).reduce((acc, v) => acc.concat({[v[0]]: v[1]}), []));
Matus Dubrava
  • 13,637
  • 2
  • 38
  • 54