2014-01-13 67 views
1

我在這裏有一個益智遊戲。我有以下的集合:將一個JSON對象分成幾個集合對象

var TagsCollection = Backbone.Collection.extend({ 
    model: TagModel, 
    parse : function(response) { 
     console.log(response); 
     // code to go 
     return response; 
    } 
}); 

現在取下面的示例JSON對象:

{ 
    id: 10149682, 
    published: "2014-01-13 08:23:00", 
    title: "Title", 
    tags: "tag1,tag2,tag3,tag4" 
} 

現在我要的是插入一些代碼,將重新映射現有的響應爲以下格式:

[{name: "tag1"}, {name: "tag2"}, {name: "tag3"}, {name: "tag4"}] 

並將其加載到集合中。 (一個重要的注意事項 - 使用Backbone/Underscore方法 - 用於例如.chain/_.reduce等)。

回答

2

您可以splittags鍵:

var tags = response.tags.split(','); 

而且map結果數組

return _.map(tags, function(tag) { 
    return {name: tag}; 
}); 
0

您也可以嘗試這樣的:

var tags= "tag1,tag2,tag3,tag4"; 

var newArr = tags.split(',').map(function(tag){ return {name: tag} }); 

重要:該作品在IE9 +中如果你需要在IE8或更高版本中運行,你需要polufill。您可以點擊說明書here

相關問題