retreiving values from a for loop and dynamically adding them to a JSON in an array
So I have a for-loop which returns for each result record a
id Name StartDate EndDate
here it is the for-loop below >
for (var i = 0; i < data.d.results.length; i++) {
}
So at the end depending on how many records returned I am going to have a few of these.
What I do want to do is as these records are created dynamically in the loop add them to a json object of mine
jsonObject= [{
id: 0, name: Name1, series: [{ start: Startdate1, end: Enddate1 }],
id: 1, name: Name2, series: [{ start: Startdate2, end: Enddate2 }],
id: 2, name: Name3, series: [{ start开发者_如何学Python: Startdate3, end: Enddate3 }],
}];
So through the loop the id's 1 get added within the object, then 2 then 3. I've been reading up on the .push method but not sure how I structure this one.
This should accomplish what you're looking for.
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js" ></script>
<script type='text/javascript' src='https://github.com/douglascrockford/JSON-js/raw/master/json2.js'></script>
<script type="text/javascript">
var data = {};
data.d = {};
data.d.results = [
["1", "Bob", "01/01/2007", "12/31/2010"],
["2", "Jim", "01/01/2007", "12/31/2010"],
["3", "Tom", "01/01/2007", "12/31/2010"]
];
var jsonObject = [];
for (var i = 0; i < data.d.results.length; i++) {
var jsonItem = {};
jsonItem.id = data.d.results[i][0];
jsonItem.name = data.d.results[i][1];
jsonItem.series = [];
var jsonSeries = {}
jsonSeries.start = data.d.results[i][2];
jsonSeries.end = data.d.results[i][3];
jsonItem.series.push(jsonSeries);
jsonObject.push(jsonItem);
}
alert(JSON.stringify(jsonObject));
</script>
</head>
<body>
</body>
</html>
You can use $.map() to make transformations like that simple. This assumes you're receiving an array of objects with properties id, Name, StartDate, and EndDate:
var jsonObject = $.map(data.d.results, function(item, i) {
return {
id: i,
name: item.Name,
series: [{ start: item.StartDate, end: item.EndDate }]
};
});
精彩评论