Simplest way to convert a JSON object to a newly structured JSON object?
I've got a JSON object that is structu开发者_如何转开发red like this:
{
"xaxis": [
"foo",
"bar",
"baz"
],
"yaxis": [
333,
992,
1365
]
}
From it I'd like to create another JSON object stuctured like this:
{
"piegraph": [
["foo",333],
["bar",992],
["baz",1365]
]
}
Doing this conversion in client-side JavaScript would save me additional development and another server round-trip to fetch what is essentially the same data.
I can employ the jQuery library if that would help.
You could use Functional JavaScript:
second = { piegraph: Functional.zip([first.xaxis, first.yaxis]) };
Assuming that your first JSON string is already parsed to an object, you just have to iterate over the elements of any of the two arrays, to build the result:
var result = { piegraph: [] }; // initialize piegraph as an empty array
var l = obj.xaxis.length;
while(l--) {
result.piegraph[l] = [ obj.xaxis[l], obj.yaxis[l] ];
}
// result will look like this:
// {"piegraph":[["foo",333],["bar",992],["baz",1365]]}
No libraries needed, just a plain sequential loop. ;)
Why can't you just use a for loop something like?
for(var i = 0; xaxis.length; i++){
piegraph.push({xaxis[i], yaxis[i]);
}
This isn't hard to do manually, but the underscore.js functional library has a bunch of very handy functions, including .zip()
:
var piegraph = _.zip( obj.xaxis, obj.yaxis );
Looks like you want to do pair-wise matching (aka "zipping") of two arrays.
Assume array1 and array2 for x and y axes and resultArray i.e. "piegraph"
jQuery.map(array1, function(item, i){
resultArray.push(new Array(array[item, array2[i]));
}
});
精彩评论