0
我找到了一些例子,並得到這個幾乎工作。我試圖比較兩個對象數組:如何遍歷2個對象數組,並通過匹配id進行合併
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其中只有1被推入
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)
你能提供預期的數組嗎? – mtamma