使用Underscore / Lo-dash更新集合对象

时间:2013-08-12 21:44:17

标签: javascript underscore.js lodash

我有两个对象集合。我迭代通过集合A,我希望当A的ObjectId与B的ObjectId匹配时,更新集合B中的Object。

这是我到目前为止所得到的:

   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();
        });

修改

链接到Fiddle

1 个答案:

答案 0 :(得分: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