gpt4 book ai didi

javascript - 使用 Angular foreach 循环重新排列 JSON

转载 作者:行者123 更新时间:2023-11-30 17:19:34 25 4
gpt4 key购买 nike

我有一个 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) ==> 将把你属性(property) Year 中的月份给你一个数组 Array.prototype.map ==> 你传入月份数组并从所有月份中取回日期的二维数组。 [].concat ==> 返回串联数组的数组。它可以接受多个数组作为参数,所以我们使用 function.apply方便地将 2D 转换为 1D。

Bin

其他简单且性能有效的方法始终是循环和添加。

关于javascript - 使用 Angular foreach 循环重新排列 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25390532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com