过滤非空或未定义的对象值

时间:2019-05-08 19:44:25

标签: javascript lodash

尝试过滤出未定义的对象值。

const activeCard = _.pickBy(cards);

activeCard的控制台输出显示以下对象。

 { cardValue1: 
   [ { account_value: '4422444443333004',
       country: 'US',
       month: '01',
       year: '2029',
       confirmation: [Object] } ],
  cardValue2: [ { account_value: undefined } ],
  cardValue3: [ { account_value: undefined } ] }

我尝试了类似的方法

const newObject = _.omitBy(activeCard, _.isNil);

// also tried to filter out at the level of _.pickBy which didnt work

const activeCard = _.pickBy(cards, (value) => { return value.length > 0; });

// output i am looking for is something like below
[ { account_value: '4422444443333004',
       country: 'US',
       month: '01',
       year: '2029',
       confirmation: [Object] } ]
// So basically, Im looking for output with 'undefined' object values filtered out.

3 个答案:

答案 0 :(得分:0)

也许使用自定义功能?

function sanitize(a) {
  let b = JSON.parse(JSON.stringify(a))
  for (const key in b) {
    if (Array.isArray(b[key])) {
      if (_.isEmpty(b[key][0])) delete b[key]
    }
  }
  return b;
}
const filteredActiveCard = sanitize(activeCard)

答案 1 :(得分:0)

使用_.filter()并用Array.some()(或破折号_.some())检查属性数组是否包含一个account_value而不是nil的数组。然后将结果展平为单个数组。

const activeCard = {"cardValue1":[{"account_value":"4422444443333004","country":"US","month":"01","year":"2029","confirmation":[null]}],"cardValue2":[{}],"cardValue3":[{}]}

const result = _.flatten(_.filter(activeCard, arr => 
  arr.some(o => !_.isNil(o.account_value))
))

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

使用lodash / fp,您可以创建一个过滤函数,方法是迭代_.some(),获取account_value并检查是否不是nil。然后将结果展平为单个数组。

const { filter, some, flow, get, negate, isNil, flatten } = _

const fn = flow(
  filter(some(flow(
    get('account_value'),
    negate(isNil)
  ))),
  flatten
)

const activeCard = {"cardValue1":[{"account_value":"4422444443333004","country":"US","month":"01","year":"2029","confirmation":[null]}],"cardValue2":[{}],"cardValue3":[{}]}

const result = fn(activeCard)

console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

答案 2 :(得分:0)

Lodash使这个超级容易。

const cards = {
 cardValue1: 
   [ { account_value: '4422444443333004',
       country: 'US',
       month: '01',
       year: '2029',
       confirmation: [Object] } ],
  cardValue2: [ { account_value: undefined } ],
  cardValue3: [ { account_value: undefined } ] 
 }

const activeCards = _(cards)
      .pickBy(v => v.length)
      .values()
      .flatten()
      .filter('account_value')
      
console.log(activeCards);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>