0

How can I convert the following object:

{
  Value1: 1,
  Value2: 3
}

into an array that looks like this:

[
 {name: Value1, position: 1},
 {name: Value2, position: 3}
]

I've tried using Object.keys, but didn't really get the desired results.

2 Answers 2

2

You can get the array of [key, value] pairs using Object.entries function.

const input = { 
 Value1: 1, 
 Value2: 3 
};

const output = Object.entries(input).map((item) => ({
  name: item[0],
  position: item[1]
}));
console.log(output);

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

Comments

0

function convertToArray(obj){
   return  Object.keys(obj).map(prop => {
      return {
           name: prop, 
           position: obj[prop]
      };
});

console.log(convertToArray({ Value1: 2}));

2 Comments

Please add some explanation to your answer such that others can learn from it
OK Nico. I thought would be self explanatory.

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.