Question

I have two collections of objects. I iterate trough collection A and I want when ObjectId from A matches ObjectId from B, to update that Object in collection B.

Here is what I got so far:

   var exerciseIds = _(queryItems).pluck('ExerciseId').uniq().valueOf();
        var item = { Exercise: null, ExerciseCategories: [] };
        var exerciseAndCategories = [];

        //this part works fine
        _.forEach(exerciseIds, function(id) {
            var temp = _.findWhere(queryItems, { 'ExerciseId': id });
            item.Exercise = temp.Exercise;
            exerciseAndCategories.push(item);
        });

        //this is problem
        _.forEach(queryItems, function (i) {
            _(exerciseAndCategories).where({ 'ExerciseId': i.ExerciseId }).tap(function (x) {
                x.ExerciseCategories.push(i.ExerciseCategory);
            }).valueOf();
        });

EDIT

Link to a Fiddle

Was it helpful?

Solution

Give this a try:

var exerciseIds = _(queryItems).pluck('ExerciseId').uniq().valueOf();
var item = {
    Exercise: null,
    ExerciseCategories: []
};
var exerciseAndCategories = [];

//this part works fine
_.forEach(exerciseIds, function (id) {
    var temp = _.findWhere(queryItems, {
        'ExerciseId': id
    });
    var newItem = _.clone(item);
    newItem.Exercise = temp.ExerciseId;
    exerciseAndCategories.push(newItem);
});

//this is problem
_.forEach(queryItems, function (i) {
    _(exerciseAndCategories).where({
        'Exercise': i.ExerciseId
    }).tap(function (x) {
        return _.forEach(x, function(item) {
            item.ExerciseCategories.push(i.ExerciseCategory);
        });
    }).valueOf();
});

// exerciseAndCategories = [{"Exercise":1,"ExerciseCategories":["biking","cardio"]},{"Exercise":2,"ExerciseCategories":["biking","cardio"]}]

Main problem was that tap returns the array, not each item, so you have to use _.forEach within that.

FIDDLE

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top