2

I have a requirement, where i am having a JSON object which should be converted to Key/value pairs array.

JSON:

Object {id: "1213115", transac_status: "Y", trans_id: "601427"....}

This should be converted to JS array like below: JS Array:

var transData = [{ id: "1213115", transac_status: "Y", trans_id: 601427".... ];

I tried the below script for the conversion.

var transData = $.map(Object , function (e2, e1) {
    return [[e2, e1]];
});

The array has not been converted as expected, Instead it has the following :-

Array[2]
, 
Array[2]
, 
Array[2]
, 
Array[2]

..... etc

5
  • You want the whole object to be contained inside an array? or create an array for every key/value? Commented Dec 12, 2015 at 14:09
  • This is somewhat confusing, your example seems like just var transData = [Object] ? Commented Dec 12, 2015 at 14:39
  • @Moin : I want the whole object to be converted as a single array. Not every kery/value as a array. Commented Dec 14, 2015 at 2:31
  • Okay. So have you tried doing it like: var obj = [{id: "1213115", transac_status: "Y", trans_id: "601427"}]; Means containing it in square brackets? Commented Dec 14, 2015 at 8:54
  • Yes @Moin! Sorry for the confusion. I need to convert JSON to the format exactly as you have mentioned above. It should be a key/Value pair (JS Object) Commented Dec 14, 2015 at 14:25

2 Answers 2

1

There is nothing wrong with your code I think. You said, that you want to produce an array with key-value pairs, which you actually do:

Array[2] , Array[2] , Array[2] , Array[2] 

This is just the output that console.log produces. If you look closer at your array you'll see, that it actually is:

[["1213115", "id"], ["Y", "transac_status"], ["601427", "trans_id"]]

Thinking about it, you probably might want to switch your key/value pair, like this:

var transData = $.map(Object , function (value, key) {
    return [[key, value]];
});

I renamed the function arguments to make things a little clearer.

Output would be:

[["id", "1213115"], ["transac_status", "Y"], ["trans_id, "601427"]]

Tipp: If you are working in a browser, you can just output the whole array with this line, which gives you a nice table-form output:

console.table(transData);

enter image description here

Is that what you are looking for? Hope that helps.

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

Comments

0

Assuming Object is a list of objects

var arr = [];

$.map(Object, function(item) {
    arr.push(item);
});

This will push each object into the array;

Example

Comments

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.