cucuru
cucuru

Reputation: 3698

how to convert Object in array saving the key

I want to change my object into an Array of this objects, this is what I have:

const myObj = {
  element1: {
    value1: 1,
    value2: 2
  },
  element2: {
    value1: 3,
    value2: 4
  },
  element3: {
    value1: 5,
    value2: 6
  }
}

What I want to get is:

const myArray = [
  {element1: {
    value1: 1,
    value2: 2
  }
  },{
  element2: {
    value1: 3,
    value2: 4
  },{
  element3: {
    value1: 5,
    value2: 6
  }
 }
]

But I don't get it, this is my choice:

const myArray = Object.keys(myObj).map(item => myObj[item]);

But I lose the "elementX" key.

What are I'm missing?

Upvotes: 3

Views: 791

Answers (2)

abdullahkady
abdullahkady

Reputation: 1071

You're just forgetting to actually include the key, aka item variable, you just include the value of such key using myObject[item].

Should be :

const myArray = Object.keys(myObject).map(item => {
  return { [item]: myObject[item] };
});

Since you forget the key, you just get the value.

Using implied returns from arrow functions with object literals, you can use an expression brackets like so: Object.keys(myObject).map(item => ({ [item]: myObject[item] }) );

Upvotes: 3

Amit Chigadani
Amit Chigadani

Reputation: 29715

You are almost there, You have to return an object instead of just properties of an object

const myArray = Object.keys(myObj).map((item) => {
      let temp = {};
      temp[item] = myObj[item];
      return temp;
    });

DEMO

Upvotes: 0

Related Questions