我有一个称为事件的json对象数组,其中包含eventId,eventName和最重要的dateofevent等字段。
[{event1},{event2},{event3}];
我需要迭代这个事件数组并过滤掉同一天发生的事件。获得这样的新对象。
"days": [
{
"date": "11-05-2015",
"events": [
{"eventId": 1, ...},
{"eventId": 2, ...},
{"eventId": 3, ...},
{"eventId": 4, ...},
]
},
如何使用Javascript或Angular有效地完成此操作?
答案 0 :(得分:0)
您可以使用日期作为键创建新对象,值是包含事件的数组。 在你有了date =>之后事件映射,将其转换为所需结构中的数组。
假设原始数据位于名为" events":
的变量中 var events = [{event 1}, {event 2}...];
var daysMap = {};
var days = [];
events.map(function(event) {
if (days[event.dateofevent] === undefined) {
days[event.dateofevent] = [];
}
days[event.dateofevent].push(event);
});
for (var day in daysMap) {
days.push({
date: day,
events: daysMap[day]
});
}
答案 1 :(得分:-1)
HTML
<div ng-app>
<span class="bold">Demonstrating filtering and sorting using Angular JS</span>
<br /><br />
<div ng-controller="ShoppingCartCtrl">
<div>Sort by:
<select ng-model="sortExpression">
<option value="Name">Name</option>
<option value="Price">Price</option>
<option value="Quantity">Quantity</option>
</select>
</div>
<br />
<div><strong>Filter Results</strong></div>
<table>
<tr>
<td>By Any: </td>
<td><input type="text" ng-model="search.$" /></td>
</tr>
<tr>
<td>By Name: </td>
<td><input type="text" ng-model="search.Name" /></td>
</tr>
<tr>
<td>By Price: </td>
<td><input type="text" ng-model="search.Price" /></td>
</tr>
<tr>
<td>By Quantity: </td>
<td><input type="text" ng-model="search.Quantity" /></td>
</tr>
</table>
<br />
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items | orderBy:mySortFunction | filter:search">
<td>{{item.Name}}</td>
<td>{{item.Price | currency}}</td>
<td>{{item.Quantity}}</td>
</tr>
</tbody>
</table>
<br />
</div>
</div>
的Javascript
function ShoppingCartCtrl($scope) {
$scope.items = [
{Name: "Soap", Price: "25", Quantity: "10"},
{Name: "Shaving cream", Price: "50", Quantity: "15"},
{Name: "Shampoo", Price: "100", Quantity: "5"}
];
$scope.mySortFunction = function(item) {
if(isNaN(item[$scope.sortExpression]))
return item[$scope.sortExpression];
return parseInt(item[$scope.sortExpression]);
}
}
CSS
.bold { font-weight:bold; }
table td{
padding: 10px;
}
table th{
font-weight: bold;
text-align: center;
}