![](/img/trans.png)
[英]Why is my JSON object showing [Array] instead of the data in javascript after reformatting?
[英]Reformatting JSON data into a Javascript Object
我有一组JSON数据,我试图将其重新格式化以遵循“时间轴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
}]
}
}
});
}
但是我返回的数据仅返回一组“日期”数组(这是JSON数据的最后日期和主题行):
timeline: {
headline: "User 1",
type: "default",
text: "tousled",
date: [{
startDate: "2014,07,7",
headline: "RE: Timeam feugiat invidunt"
}]
}
您将如何遍历JSON数据,以便它返回所有给定的日期和主题行集?
嗨,请参阅此处的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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.