3

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?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

I guess this would always return key as item, but not element1, element2 etc
perfect! that was my problem, the only point is change item by [item], because if not all elements has "item" instead it value
Missing a closing bracket } on last line of your code.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.