问题
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
回答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);
Is that what you are looking for? Hope that helps.
回答2:
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
来源:https://stackoverflow.com/questions/34240678/converting-json-object-to-js-key-value-pairs-array