将JSON对象转换为JS键/值对Array [英] converting JSON object to JS Key/value pairs Array
问题描述
我有一个要求,我有一个JSON对象应该转换为键/值对数组。
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"....}
这应该转换为JS数组,如下所示:
JS Array:
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]
.....等
推荐答案
我认为你的代码没有任何问题。你说,那个你想要生成一个具有键值对的数组,你实际上是这样做的:
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]
这只是 console.log
生成。如果你仔细观察阵列,你会看到它实际上是:
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.
输出为:
[["id", "1213115"], ["transac_status", "Y"], ["trans_id, "601427"]]
Tipp:如果你在工作一个浏览器,你可以用这一行输出整个数组,这给你一个很好的表格输出:
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.
这篇关于将JSON对象转换为JS键/值对Array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!