0808
0808

Reputation: 21

I want to Convert Object to Array

I have an object like this:

var jsonObject = Object {transid: "104", amt: "750.00", dt: "2015-04-28 08:12:22", code: "11222", shop: "Joes Cafe"}

I tried converting it to an array like this:

var jsArray  =  Object.keys(jsonObject).map(function(k) { return jsonObject[k] });

and I get a result like this:

["104", "750.00", "2015-04-28 08:12:22", "11222", "Joes Cafe"]

But I want jsArray to be like this:

[{transid: "104", amt: "750.00", dt: "2015-04-28 08:12:22", code: "11222", shop: "Joes Cafe"}]

How do I go about it?

Upvotes: 0

Views: 35

Answers (2)

Felix Kling
Felix Kling

Reputation: 817128

It couldn't be simpler.

You actually don't have to convert anything here. You just have to create the array and add the object as element:

var arr = [obj]; // [ ] denotes an array literal in this case

Learn more about arrays.

Upvotes: 1

R3tep
R3tep

Reputation: 12864

You can create an array, and insert your object into it.

var array = [];
var jsonObject = {
  transid: "104",
  amt: "750.00",
  dt: "2015-04-28 08:12:22",
  code: "11222",
  shop: "Joes Cafe"
}
array.push(jsonObject);
document.write(JSON.stringify(array));

Upvotes: 1

Related Questions