Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 953
noorayu Avatar asked Jun 25 '26 22:06

noorayu


2 Answers

Just use bracket.

let obj = {0: "item A", 1: "item B", 2: "item C"}
console.log([obj]);
like image 128
Mihai Alexandru-Ionut Avatar answered Jun 28 '26 12:06

Mihai Alexandru-Ionut


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 )
like image 23
Matías Fidemraizer Avatar answered Jun 28 '26 12:06

Matías Fidemraizer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!