我找到了一些例子,并且几乎可以使用。我试图比较2个对象数组:
var responseExercises = [{
"exerciseId": 44,
"exerciseName": "Double Leg Press with Treading",
"exerciseBenefits": "Core Control, Axial Elongation",
"exerciseSprings": [],
"isHidden": false,
"workoutId": null,
"workouts": [],
"exerciseImages": [],
"exerciseRepetitions": []
}, {
"exerciseId": 46,
"exerciseName": "Bent Arm Arcs with Quarter Circles",
"exerciseBenefits": "Improved Posture, Upper Torso Alignment",
"exerciseSprings": [],
"isHidden": false,
"workoutId": null,
"workouts": [],
"exerciseImages": [],
"exerciseRepetitions": []
}, {
"exerciseId": 47,
"exerciseName": "Bridging with Leg Press",
"exerciseBenefits": "Spine Articulation, Upper Torso Alignment",
"exerciseSprings": [],
"isHidden": false,
"workoutId": null,
"workouts": [],
"exerciseImages": [],
"exerciseRepetitions": []
}];
var responseSprings = [{
"clientExerciseSpringId": 1,
"clientExerciseSpringCount": "2",
"clientExerciseSpringColor": "blue",
"clientExerciseSpringLevel": "bottom",
"exerciseId": 44,
"clientWorkoutId": 4,
"clientWorkout": null
}, {
"clientExerciseSpringId": 2,
"clientExerciseSpringCount": "1",
"clientExerciseSpringColor": "blue",
"clientExerciseSpringLevel": "bottom",
"exerciseId": 44,
"clientWorkoutId": 4,
"clientWorkout": null
}, {
"clientExerciseSpringId": 3,
"clientExerciseSpringCount": "2",
"clientExerciseSpringColor": "yellow",
"clientExerciseSpringLevel": "bottom",
"exerciseId": 46,
"clientWorkoutId": 4,
"clientWorkout": null
}, {
"clientExerciseSpringId": 4,
"clientExerciseSpringCount": "1",
"clientExerciseSpringColor": "yellow",
"clientExerciseSpringLevel": "top",
"exerciseId": 46,
"clientWorkoutId": 4,
"clientWorkout": null
}, {
"clientExerciseSpringId": 5,
"clientExerciseSpringCount": "2",
"clientExerciseSpringColor": "blue",
"clientExerciseSpringLevel": "bottom",
"exerciseId": 47,
"clientWorkoutId": 4,
"clientWorkout": null
}];
我需要将responseSprings推送到匹配的responseExercise。我现在得到的结果是,如果有多个匹配的exerciseSprings,其中只有一个被推入
responseSprings.responseSprings
阵列。我在项目中使用下划线,因此可以使用它,如果有更好的解决方案。
vm.combineResponse = function(responseExercises, responseSprings) {
console.log($.map(responseExercises, function(exercise) {
var spring = $.grep(responseSprings, function(spring) {
return spring.exerciseId === exercise.exerciseId;
})[0];
exercise.exerciseSprings.push(spring);
return exercise;
}));
};
vm.combineResponse(responseExercises, responseSprings)
答案 0 :(得分:1)
使用for循环怎么样?看起来很简单,没有图书馆。
for (var i = 0; i < responseExercises.length; i++) {
var exercise = responseExercises[i];
var id = exercise.exerciseId;
for (var j = 0; j < responseSprings.length; j++) {
var spring = responseSprings[j];
if (spring.exerciseId == id) {
exercise.exerciseSprings.push(spring);
}
}
};
console.log(responseExercises);