Filtering object properties based on value

前端 未结 7 781
孤独总比滥情好
孤独总比滥情好 2020-12-14 16:40

Is there some elegant way of filtering out falsey properties from this object with lodash/underscore? Similar to how _.compact(array) removes falsey elements fr

7条回答
  •  难免孤独
    2020-12-14 17:19

    Here are two vanilla javascript options:

    A.: Iterate over the object's keys and delete those having a falsey value.

    var obj = {
      propA: true,
      propB: true,
      propC: false,
      propD: true,
    };
    
    Object.keys(obj).forEach(key => {
      if (!obj[key]) delete obj[key];
    });
    
    console.log(obj);

    See Object.keys() and Array.prototype.forEach()

    B.: Iterate over the object's keys and add truthy values to a new object.

    var obj = {
      propA: true,
      propB: true,
      propC: false,
      propD: true,
    };
    
    var filteredObj = Object.keys(obj).reduce((p, c) => {    
      if (obj[c]) p[c] = obj[c];
      return p;
    }, {});
    
    console.log(filteredObj);

    See Object.keys() and Array.prototype.reduce()

提交回复
热议问题