![](/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.