使用角度foreach循环重新排列JSON

时间:2014-08-19 18:30:45

标签: javascript json angularjs foreach

我有一个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
    }

2 个答案:

答案 0 :(得分:2)

只是详细说明我的评论: -

您可以通过这种方式将分散在不同月份的数组合并到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) ==&gt;会在您的属性Year中为您提供数组的月份 Array.prototype.map ==&gt;你传入了几个月的数组,并从几个月开始回归2D数组。 [].concat ==&gt;返回连接数组的数组。它可以采用多个数组作为参数,因此我们可以方便地使用function.apply将2D转换为1D。

<强> Bin

其他简单且性能有效的方法总是循环并添加。

答案 1 :(得分:0)

Array.prototype.concat 允许将两个数组合并为一个。但是,它只是javascript并且与Angular无关,这样做的方式就像:

var a =  [{"day":"10","title":"day","summary":"summary","description":"ok","_id":"53f25185bffedb83d8348b22"}];
var b = [{"day":"3","title":"day","summary":"summary","description":"ok","_id":"53f25185bffedb83d8348b22"}];

var c = a.concat(b); // returns the concatenated array.