Javascript or Ruby. Reformat a JSON object
I need to turn this JSON object:
[
[
"email@email.com"
],
[
"email2@email.com"
],
[
"email3@email.com"
],
[
"email4@email.com"
]
]
Into this:
{
"data": [
{
"email": "email@email.com"
},
{
"email": "email2@email.com"
},
{
"email": "email3@email.com"
},
{
"email": "email4@email.com"
}
] }
H开发者_运维问答ow is this done?
Well, that's really just an array of arrays, but that's besides the point. Just loop through the array of arrays and push the relevant data onto the new array in your object:
var my_new_object = {};
my_new_object['data'] = [];
for (var i = 0; i < your_array.length; i++) {
my_new_object.data.push({"email": your_array[i][0]});
}
Working demo.
Javascript:
var original = [
[
"email@email.com"
],
[
"email2@email.com"
],
[
"email3@email.com"
],
[
"email4@email.com"
]
];
var output = {};
output.data = new Array();
for(var i=0;i<original.length;i++){
var o = new Object();
o.email = original[i][0];
output.data.push(o);
}
you can test it here: http://jsfiddle.net/v3fnk/
var data=[["email@email.com"],["email2@email.com"],["email3@email.com"],["email4@email.com"]];
for (var i in data) {
for (var x in data[i]) {
$("#info").append(data[i][x] + '<br/>');
}
}
精彩评论