问题
I have this json structure.
x=[{
"value": 1.37,
"date_transacted": "2015-01-01"
}]
From this json structure, I want to produce the following json structure;
y1=[{
c: [{
v: "2015-01-01"
},
{
v: "1.37"
}]
}]
I have written the code to do this. It looks like this;
var y1 = [{ c:[ {"v":x[0].value}, {"v":x[0].date_transacted} ] }];
My problem comes when x
has several json key/value pairs. Something that look like this;
x=[{
"value": 1.37,
"date_transacted": "2015-01-01"
},
{
"value": 1.62,
"date_transacted": "2015-02-01"
},
{
"value": 1.83,
"date_transacted": "2015-03-01"
}]
What is an effective way to iterate my code through the array of objects to produce the desired json structure which should look like this?
y=[{
c: [{
v: "2015-01-01"
},
{
v: "1.37"
}]
},
{
c: [{
v: "2015-01-02"
},
{
v: "1.62"
}]
},
{
c: [{
v: "2015-01-03"
},
{
v: "1.83"
}]
}]
回答1:
The other answers here (except @user2415266) are not dynamic, hard-coded to accept an exact input, and are not particularly reusable. They will fail if you have more than 2 properties, or in @Siguza's case, also if you have properties not called 'date_transacted' and 'value'.
function restructureJson(obj) {
var output = {c:[]};
for (var i in obj) {
output.c.push({v:obj[i]});
}
return output;
}
This function is reusable on any array of objects, of any size, containing any number of properties.
// Simple example
var json1 = [{
"value": 1.37,
"date_transacted": "2015-01-01"
}];
// More complex
var json2 = [{
"value": 1.37,
"date_transacted": "2015-01-01",
"another_value": "test",
"more": "12356"
},
{
"value": 1.62
},
{
"value": 1.83,
"date_transacted": "2015-03-01",
"stuff": "124334654567"
}];
// Map the function to the arrays
a = json1.map(restructureJson);
b = json2.map(restructureJson);
回答2:
var y1=[];
for(var i=0;i<x.length;i++){
y1[i]= [{ c:[ {"v":x[i].value}, {"v":x[i].date_transacted} ] }];
}
回答3:
As a single statement:
y = x.map(function(e)
{
return {
c:
[
{
v: e.value
},
{
v: e.date_transacted
}
]
};
});
回答4:
Both other answers only work if the objects in x have the exact 2 properties. A way to do it regardless of the amount of properties:
y = [];
for(var i = 0, i < x.length; i++){
var obj = {c:[]};
for(var prop in x[i]){
obj.c.push({v:x[i][prop]})
}
y.push(obj);
}
Edit: with map
y = x.map(function(e)
{
var obj = {c: []};
for(var prop in e){
obj.c.push({v:e[prop]})
}
return obj;
});
来源:https://stackoverflow.com/questions/33298774/how-do-i-iterate-over-this-json-structure-to-produce-another-structure