我使用Angular和Lodash来处理对象和数组。
鉴于此:
$scope.week = ['monday','tuestday','wednesday','thursday','friday','saturday','sunday']
$scope.points = [
{ day: 'monday', points: 30 },
{ day: 'wednesday', points: 60 }
]
...我想得到这个结果:
$scope.result = [30, 0, 60, 0, 0, 0, 0];
所以我必须将数组与对象进行比较,但我想避免使用多个循环。
请参阅JS Fiddle。
P.S:我不使用jQuery。
答案 0 :(得分:0)
你可以这样做:
var temp = $scope.points.reduce((obj, el) => (obj[el.day] = el.points, obj), {});
$scope.result = $scope.week.map(day => temp[day] || 0);
temp 变量是按天键入的对象,并将与该日相关联的点作为值提供。给出示例数据,它看起来像:
{
monday: 30,
wednesday: 60
}
它允许在第二个语句中进行有效查找。
请参阅JS fiddle
注意:请务必更正周数组('tuestday')中的拼写错误。
答案 1 :(得分:0)
您可以使用lodash的_.map和_.findIndex方法或简单的Array类,如下所示
$scope.result =_.map($scope.week, function (v, i) {
var index = _.findIndex($scope.points, { 'day': v})
if (index > -1) {
return $scope.points[index].points
} else {
return 0
}
})
其中_是lodash的一个实例。
答案 2 :(得分:-1)
如果是数据结构,可以使用Javascript数组方法,如下所示:
var filteredPoints = $scope.points.filter((point) => {
return $scope.week.indexOf(point.day) != -1;
});
$scope.result = filteredPoints.map((point) => { return point.points });