我有一组JSON数据,我正在尝试重新格式化以遵循'Timeline JS'中描述的javascript对象模型。
这是原始的JSON数据,存储在变量“messages”中:
{
"user_id": 1,
"subject_line": "Timeam feugiat invidunt",
"type": "feugiat",
"date": "2014,07,5",
"message": "Butcher letterpress et tousled ea. Id do artisan"
},
{
"user_id": 1,
"subject_line": "RE: Timeam feugiat invidunt",
"type": "feugiat",
"date": "2014,07,7",
"message": "Butcher letterpress et tousled ea."
}
需要将JSON数据重新格式化为以下Javascript对象语法:
timeline: {
headline: "User 1", // messages.user_id
type: "default",
text: "tousled",
date: [{
startDate: "2014,07,5", //messages.date
headline: "Timeam feugiat invidunt" //messages.subject_line
},
{
startDate: "2014,07,7",
headline: "RE: Timeam feugiat invidunt"
}]
}
这是我目前的代码:
function(){
var messagesData;
// API data fetched and stored in 'messages'
messages.each(function(data){
data = data.toJSON();
messagesData = {
timeline: {
headline: "User " + data.user_id,
type: "default",
text: "tousled",
date: [{
startDate: data.date,
headline: data.subject_line
}]
}
}
});
}
然而,我回来的数据只返回一组'date'数组(这是JSON数据的最后一个日期和主题行):
timeline: {
headline: "User 1",
type: "default",
text: "tousled",
date: [{
startDate: "2014,07,7",
headline: "RE: Timeam feugiat invidunt"
}]
}
如何循环访问JSON数据,以便它返回所有给定的日期和主题行?
答案 0 :(得分:0)
嗨,请看这里http://plnkr.co/edit/twLsdzFZHmCwMvzwrux6?p=preview应该对你有帮助。
var messages = [{
"user_id": 1,
"subject_line": "Timeam feugiat invidunt",
"type": "feugiat",
"date": "2014,07,5",
"message": "Butcher letterpress et tousled ea. Id do artisan"
},
{
"user_id": 1,
"subject_line": "RE: Timeam feugiat invidunt",
"type": "feugiat",
"date": "2014,07,7",
"message": "Butcher letterpress et tousled ea."
}];
var storyjs_data = {
"timeline": {
"headline": "User" + messages[0].user_id,
"type": "default",
"text": "tousled",
"date": []
}
};
$(messages).each(function(indx, message) {
var _date = {
"startDate": message.date,
"headline": message.subject_line,
};
storyjs_data.timeline.date.push(_date);
});