javascript 使用 Underscore / Lo-dash 更新集合对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18197176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Update collection object using Underscore / Lo-dash
提问by hyperN
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.
我有两个对象集合。我遍历集合 A,我希望当 A 中的 ObjectId 与 B 中的 ObjectId 匹配时,更新集合 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
链接到小提琴
回答by kalley
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.
主要问题是tap
返回数组,而不是每个项目,因此您必须在其中使用_.forEach
。