选择并显示仅大于0的值

时间:2016-03-10 06:40:17

标签: javascript json nested lodash

我有以下数据结构,

var stat = {
  meta : 0,

  added : {
    menuSessions: {
      items: 0,
      fields: 0
    },

    menuCats: {
      items: 0,
      fields: 0
    },

    menuItems: {
      items: 0,
      fields: 0
    }
  },

  updated: {
    menuSessions: {
      items: 0,
      fields: 0
    },

    menuCats: {
      items: 0,
      fields: 3
    },

    menuItems: {
      items: 3,
      fields: 0
    }
  },

  deleted: {
    menuSessions: 1,
    menuCats: 10,
    menuItems: 0
  }
};

并希望使用lodash

推导出如下结构
var stat = {
  //meta not shown
  //added not shown
  updated: {
    menuCats: {
      //items not show etc..
      fields: 3
    },

    menuItems: {
      items: 3,
    }
  },

  deleted: {
    menuSessions: 1,
    menuCats: 10,
  }
};

我尝试了很多方法,例如使用filter方法如下或纯JS(如果更容易),

var json  = _.filter(stat, function(statEle){

    return statEle > 0 || ((statEle.added && statEle.added.menuSessions) && (statEle.added.menuSessions.items > 0 || statEle.added.menuSessions.fields > 0))
    || ((statEle.updated && statEle.updated.menuSessions) && (statEle.updated.menuSessions.items > 0 || statEle.updated.menuSessions.fields > 0))
    || ((statEle.deleted && statEle.deleted.menuSessions) && (statEle.deleted.menuSessions > 0))
    || ((statEle.added && statEle.added.menuCats) && (statEle.added.menuCats.item > 0 || statEle.added.menuCats.fields > 0))
    || ((statEle.added && statEle.added.menuItems) && (statEle.added.menuItems.items > 0 ||  statEle.added.menuItems.fields > 0))
    || ((statEle.deleted && statEle.deleted.menuItems) && (statEle.deleted.menuItems > 0))
    || ((statEle.deleted && statEle.deleted.menuCats) && (statEle.deleted.menuCats > 0));

  });

如 - Lodash: how do I use filter when I have nested Object?所示,但由于此结构需要过滤动态属性名称,因此失败。

我对JSON过滤器和lodsash堆栈都很陌生,并希望有任何有用的参考/示例让我能够完成这个:)谢谢

1 个答案:

答案 0 :(得分:1)

如果您将_.mapValues_.pickBy合并在一起 - 那就是您的回答:pickByRecursive

var pickByRecursive = function (object, predicate) {
    return _.pickBy(_.mapValues(object, function (value) {
        return _.isObject(value) ? pickByRecursive(value, predicate) : value;
    }), function (value) {
        return _.isObject(value) ? !_.isEmpty(value) : predicate(value);
    });
};

_.chain

var pickByRecursive = function (object, predicate) {
    return _.chain(object)
        .mapValues(function (value) {
            return _.isObject(value) ? pickByRecursive(value, predicate) : value;
        })
        .pickBy(function (value) {
            return _.isObject(value) ? !_.isEmpty(value) : predicate(value);
        })
    .value();
};

像这样使用:

pickByRecursive(stat, function (value) {
    return value > 0;
});