简体   繁体   中英

Using Lodash to filter 2 Collections

I'm stumped on how to do the following. I have 2 objects:

newPriceList:

[{id:1, updatedPrice:22}, {id:4, updatedPrice:23}]

currPriceList:

[{id:1, price:200, name:"carrot}, {id:2, price:100, name:apple}]

If an object has an updated price, then the price is updated, if not then the price stays the same. Ideally I want to return a result that looks like this:

[{id:1, price:22},{id:2, price:100}, {id:3, price:23}]

To do this, I'm getting a list of the unchanged prices and appending it to the new prices however, I can't seem to figure out how to get a list of the unchanged prices. I'm also wondering if it's possible to do this all in 1 step.

var unChangedPrices = _(currPriceList).reject('id').at(newPriceList.id);

If you can rename "updatedPrice" to "price" this can made simple like this

_.forEach(p1, function(obj){
    _.merge(_.find(p2, {"id": obj.id}), obj)
});

This is how it will look if you don't change the name,

在此处输入图片说明

Update:

Use this to have everything in p1 included in p2, even if its id does not match

_.forEach(p1, function(obj){
    var p2Obj = _.find(p2, {"id": obj.id});
    if(p2Obj){
      _.merge(p2Obj, obj);
    }else{
      p2 = _.concat(p2,[p2Obj]);
    }
});
var res = _.map(currPriceList, function(item) { // thru each item
    return _.chain(newPriceList)
        .find({id: item.id}) // find item from new list
        .thru(function(newItem) {
            if (!_.isUndefined(newItem)) { 
                item = _.merge({}, item, {
                    price: newItem.updatedPrice // set value from new item
                });
            }
            return _.omit(item, 'name'); // remove name key
        })
       .value();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM