noorayu
noorayu

Reputation: 31

Convert Object to Array Typescript

I have an object

{0: "item A", 1: "item B", 2: "item C"}

How can I convert the object to become array like this

[{0: "item A", 1: "item B", 2: "item C"}]

For now I have tried Object.keys(obj) but it returns each element in my object to array.

Really needs help. Thank you for helping

Upvotes: 3

Views: 14067

Answers (2)

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64933

Also, there's an specific Array function for this matter: Array.of:

console.log ( Array.of ( 1 ) )

This is more functional-friendly:

const pipe = funs => x => funs.reduce( ( r, fun ) => fun ( r ), x )
const append = x => array => [ ...array, x ]
const sum = values => values.reduce ( ( r, value ) => value + r )

const result = pipe ( [
   Array.of,
   append ( 2 ),
   sum
] ) ( 1 )

console.log ( result )

Upvotes: 1

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48337

Just use bracket.

let obj = {0: "item A", 1: "item B", 2: "item C"}
console.log([obj]);

Upvotes: 8

Related Questions