0

Given a Javascript object with key values to Array of objects?

Example:

var data = { id: 1, first_name: "George", last_name: "Bluth", avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg" }

Result should be:

[
  { id: 1, first_name: "George", last_name: "Bluth", avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg" }
]
6
  • 3
    Have you tried anything at all? If yes please post the code. Commented Apr 5, 2019 at 5:29
  • I referred this: stackoverflow.com/questions/26795643/…. But the result it gets, i dont want that @KrishnaPrashatt Commented Apr 5, 2019 at 5:31
  • How JS object is invalid? I have just made for an example, if its wrong i will modify the example @AmardeepBhowmick Commented Apr 5, 2019 at 5:33
  • 1
    right, now ... so, just data = [data] should do it Commented Apr 5, 2019 at 5:35
  • var result = []; result.push(data); Commented Apr 5, 2019 at 5:36

3 Answers 3

0

Just do [data]:

var data = { id: 1, first_name: "George", last_name: "Bluth", avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg" };
var arr = [data];
console.log(arr);

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

Comments

0

if you have data as it is, and want it in an array

data = [data];

see snippet

var data = { id: 1, first_name: "George", last_name: "Bluth", avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg" }

data = [data];

console.log(JSON.stringify(data));

Comments

0

You can create an array and initialize it with the data variable:

const data = { id: 1, first_name: "George", last_name: "Bluth", avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg" };
const result = [data];

console.log(result);

2 Comments

How is your answer different than @Jack Bashford's ?
@OnurArı I just didn't copied from him.. the difference is that he answered a few seconds before me

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.