创建具有动态属性的对象数组
Create object array with dynamic properties
在targetData数组中,对象具有属性("一月"等)取自源数组....我无法将源事件转换为目标数据数组。
var sourceEvents =[
{
"title": "Course Tile1",
"details": "Webex| Advanced",
"month": "January"
},
{
"title": "Course Tile1",
"details": "Webex| Advnced",
"month": "february"
},
{
"title": "Course Tile1",
"details": "Webex| Advnced",
"month": "febrary"
}];
var TargetData =[
{"january":
[
{
"title": "Course Tile1",
"details": "Webex| Advanced"
},
{
"title": "Course Tile2",
"details": "Webex| Advanced",
}
]
},
{ "Feb":[
{
"title": "Course Tile3",
"details": "Webex| Advanced"
},
{
"title": "Course Tile4",
"details": "Webex| Advanced"
}]
}
]
我需要使用 ng-repeat 来循环生成的数组。
很难
遍历您显示的结构。我会建议这样做:
var targetData = [
{
"month": "january",
"entries": [
{
"title": "Course Tile1",
"details": "Webex| Advanced"
}, {
"title": "Course Tile2",
"details": "Webex| Advanced",
}
]
},
{
"month": "february",
"entries": [
{
"title": "Course Tile3",
"details": "Webex| Advanced"
},
{
"title": "Course Tile4",
"details": "Webex| Advanced"
}
]
}
];
这样,您就嵌套了ng-repeat
s:一个嵌套几个月,下一个嵌套一个月中的条目。
在这种情况下,通过循环源数据和条目月份的临时索引来生成相当容易:
var sourceEvents = [
{
"title": "Course Tile1",
"details": "Webex| Advanced",
"month": "January"
},
{
"title": "Course Tile1",
"details": "Webex| Advnced",
"month": "February"
},
{
"title": "Course Tile1",
"details": "Webex| Advnced",
"month": "February"
}
];
var months = Object.create(null);
var targetData = [];
sourceEvents.forEach(function(event) {
var month = event.month;
var entry = months[month];
if (!entry) {
months[month] = entry = {
month: month,
entries: []
};
targetData.push(entry);
}
entry.entries.push({
title: event.title,
details: event.details
});
});
document.body.innerHTML =
"<pre>" + JSON.stringify(targetData, null, 4).replace(/</g, "<") + "</pre>";
注意:您的源数据有几个拼写错误,我已经在上面修复了这些错别字。
旁注:我在上面使用了targetData
而不是TargetData
,因为它更符合大多数 JavaScript 风格指南。
注意引号或缺少引号:
var sourceEvents = [
{
title:"Course Tile1",
details:"Webex| Advanced",
month:january
},
{
title:"Course Tile1",
details:"Webex| Advnced",
month:february
},
{
title:"Course Tile1",
details:"Webex| Advnced",
month:february
}
];
var january = [
{
title:"Course Tile1",
details:"Webex| Advanced"
},
];
var february = [
{
title:"Course Tile1",
details:"Webex| Advanced"
},
];
var targetEvents = [
{
january, february,
}
];
相关文章:
- Javascript(Angular)从一个对象数组到第二个数组查找值
- 在Javascript中转换对象数组
- 在JavaScript中通过索引从对象数组中获取值
- Backbone虹吸以获取对象数组
- 如何在DataTables 2.1中迭代对象数组
- Javascript-根据赋值顺序,按键合并对象数组
- 将事件附加到对象/数组
- jQuery$.inArray()总是返回-1和一个对象数组
- javascript处理一个对象数组以获得一个新的对象数组
- javascript在数组中获取对象数组中键的所有不同值
- 在对象数组中查找多个值的d3范围
- Undercore.js获取对象数组中键对象的值
- 在mongoose中使用正则表达式在对象数组中进行查询搜索
- 如何通过json对象数组为嵌套对象赋值
- 如何循环通过2个对象数组并通过匹配id进行合并
- 为对象数组创建列表项
- 如何使用javascript合并两个对象数组
- JSON到对象数组,并向每个对象添加项
- JavaScript:从对象数组中获取唯一值及其计数
- 按不同项目对对象数组进行排序