【问题标题】:Lodash : _Filter, but returns an array of objects with specific keysLodash:_Filter,但返回具有特定键的对象数组
【发布时间】:2021-10-29 11:14:45
【问题描述】:

我正在制作一个比较两个对象数组并返回两个对象子集数组的函数。第一个返回的数组是一组未包含在第二个 prop 中传递的数组中的对象,第二个返回的数组是一组未包含在第一个数组中但现在包含在第二个数组中的对象。

这可行,但是,我想添加一个额外的功能来返回具有特定键的第二个数组。无论如何在过滤器函数中使用 lodash“pickBy”功能,还是我必须创建一个额外的递归部分?

function extract_removed_new (before, after, matching, pickBy = [])  {

let before_ = cloneDeep(before)
let new_ = _.filter(after, (item) => {
    let index_ = _.findIndex(before_, function (i) {
        return _.get(i, matching) == _.get(item, matching)
    })
    if(index_ !== -1) {
        before_.splice(index_, 1)
        return false
    }
    if(pickBy.length > 0) {
        return _.pickBy(item, function(value, key) {
            if(key in pickBy) {
                return true
            }
        });
    }
    return true
})
return [before_, new_]

}

【问题讨论】:

    标签: javascript lodash


    【解决方案1】:

    使用 lodash compact 和 map 我能够得到我需要的东西。

    function extract_removed_new (before, after, matching, pickBy = [])  {
    
    let before_ = cloneDeep(before)
    let new_ = _.compact(_.map(after, (item) => {
        let index_ = _.findIndex(before_, function (i) {
            return _.get(i, matching) == _.get(item, matching)
        })
        if(index_ !== -1) {
            before_.splice(index_, 1)
            return false
        }
        if(pickBy.length > 0) {
            return _.pickBy(item, function(value, key) {
                if(pickBy.includes(key)) {
                    return true
                }
            });
        }
        return item
    }))
    return [before_, new_]
    

    }

    【讨论】:

      猜你喜欢
      • 2018-04-11
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      • 2016-09-16
      • 2020-09-27
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多