我有一个ng-repeat返回对象数组,如下所示:
[{"day":"10","title":"day","summary":"summary","description":"ok","_id":"53f25185bffedb83d8348b22"}] [{"day":"3","title":"day","summary":"summary","description":"ok","_id":"53f25185bffedb83d8348b22"}]
我想拉出对象并将其推入另一个数组,以便将其格式化为:
[ {"day":"10","title":"day","summary":"summary","description":"ok","_id":"53f25185bffedb83d8348b22"}, {"day":"3","title":"day","summary":"summary","description":"ok","_id":"53f25185bffedb83d8348b22" }]
目标是在数组上使用orderBy。是否可以将JSON重组为这种格式,然后访问数据?
这是我的观点供参考:
<div class="calDynamic" data-ng-repeat="n in [] | range:100"> <div ng-repeat="cal in calendar[n].year | filterKey:month"> <p>{{cal}}</p> </div> </div>
我的JSON格式:
{ "_id" : ObjectId("53f252537d343a9ad862866c"), "year" : { "December" : [], "November" : [], "October" : [], "September" : [], "August" : [], "July" : [ { "day" : "21", "title" : "u", "summary" : "u", "description" : "ok", "_id" : ObjectId("53f252537d343a9ad862866d") } ], "June" : [], "May" : [], "April" : [], "March" : [], "February" : [], "January" : [] }, "__v" : 0 }, { "_id" : ObjectId("53f252537d343a9ad862866c"), "year" : { "December" : [], "November" : [], "October" : [], "September" : [], "August" : [], "July" : [ { "day" : "3", "title" : "u", "summary" : "u", "description" : "ok", "_id" : ObjectId("53f252537d343a9ad862866d") } ], "June" : [], "May" : [], "April" : [], "March" : [], "February" : [], "January" : [] }, "__v" : 0 }
只是详细说明我的回答:-
您可以通过这种方式将各个月分散的阵列合并为1个阵列。
//obj has the the array result that is the input var temp = []; var result = temp.concat.apply(temp,obj.map(function(itm){ //Get each object in the source array that hold the year. return temp.concat.apply(temp, Object.keys(itm.year).map(function(key){ //Get Month for each yeah and flatten it out return itm.year[key]; //Get day array for each of the month in each year })); }));
Object.keys(obj.year)==>将给您属性中的月份Year到一个数组 Array.prototype.map==>您传入月份数组,然后从所有月份中获得2D天数组。 [].concat==>返回级联数组的数组。它可以接受多个数组作为参数,因此我们可以function.apply方便地将2D转换为1D。
Object.keys(obj.year)
Year
Array.prototype.map
[].concat
function.apply
箱子
其他简单且性能有效的方法始终是循环添加。