2013-08-12 1 views
0

У меня есть две коллекции объектов. Я итерацию корыто коллекции A, и я хочу, когда ObjectId от A соответствует ObjectId из B, чтобы обновить этот объект в коллекции В.Обновить объект коллекции с помощью подстроки/подлодки

Вот что я получил до сих пор:

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

Ссылка на Fiddle

ответ

1

Дайте это попробовать:

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"]}] 

Основная проблема заключалась в том, что tap возвращает массив, а не каждый элемент, поэтому вам нужно использовать _.forEach.

FIDDLE

+0

Не помогло, когда я пишу эту строку кода: Logger.log (exerciseAndCategories) ;, я могу видеть, что ExerciseCategories: все еще пусты, поэтому коллекция exerciseAndCategories не была обновлена ​​ – hyperN

+0

Обновлены скрипка. Нужно «возвращать» из 'tap' – kalley

+0

Спасибо за скрипку, но я не получил результат, которого я ожидал, может быть, мой вопрос был недостаточно ясен, я отредактировал свой бит скрипта и добавил комментарий о том, как я хочу, чтобы результат выглядел как – hyperN

Смежные вопросы