0

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?

1
  • 1
    Please note that nothing you posted has anything to do with JSON. What you have is a JavaScript object. Commented May 12, 2015 at 13:15

2 Answers 2

1

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));

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

Comments

1

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.

2 Comments

this makes the array multidimensional. I want the array like the object. How do I do that?
@0808: this creates exactly what you claim you want. Not sure what you mean by "I want the array like the object.". Arrays and objects are two different data structures (conceptually). They are used for different purposes.

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.