3

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

2
  • 1
    just enclosed the object in []? like, obj = [obj]; Commented May 31, 2018 at 7:40
  • thank you for replying. but what is the difference when i create a new empty array and push into it Commented May 31, 2018 at 7:42

2 Answers 2

8

Just use bracket.

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

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

Comments

1

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 )

1 Comment

@noorayu No problem

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.