Rocshy
Rocshy

Reputation: 3509

Typescript create array from object

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.

Upvotes: 0

Views: 77

Answers (2)

Wakeel
Wakeel

Reputation: 5020


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

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

Upvotes: 0

Derek Wang
Derek Wang

Reputation: 10204

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

Upvotes: 2

Related Questions