【问题标题】:Lodash and map / filter / keys - better implementation?Lodash 和 map / filter / keys - 更好的实现?
【发布时间】:2015-05-15 20:07:42
【问题描述】:

我有一些数据:

this.shoes = {
    {id: 1001, color: "red", cost: 100},
    {id: 1002, color: "red", cost: 50},
    {id: 1003, color: "blue", cost: 0}
}

我正在使用 lodash 和本机实现的组合,并且想知道是否有更简洁的方式只使用 lodash。

我有什么:

var shoes = this.shoes;
var avail = _.keys(shoes).filter(function(s){
               return shoes[s].cost > 0;
            }).map(function(){
                // return some data
            });

我将“this.shoes”放入变量的原因是因为我需要“this”对周围的对象保持完整。如果我将“this.shoes”放在 _.keys() 中,它就不起作用。如果有办法“绑定”我的内容以应用于所有也可以工作的 lodash 方法。

我缺乏 lodash 专业知识,所以很好奇我是否可以缩短这个时间。 谢谢。

【问题讨论】:

  • 为什么在变量中还需要this.shoes?你有功能吗?您也可以显示周围的代码吗? shoes 是一个数组吗?它看起来不像一个有效的数组。

标签: javascript lodash


【解决方案1】:

您的this.shoe 应该是一个类似的数组

 this.shoes = [
    {id: 1001, color: "red", cost: 100},
    {id: 1002, color: "red", cost: 50},
    {id: 1003, color: "blue", cost: 0}
];

那么你可以这样做:

var avail = _.filter(this.shoes, function(s){
               return s.cost > 0;
            }).map(function(){
                // return some data
            });

当然,您不需要将“this.shoes”放入变量中。

【讨论】:

  • this.shoes 不能是数组,我需要 obj 作为查找。我不能把它作为一个数组来做。我可以,但我必须遍历数组,找到相应的 ID --- 更新它,重新插入它等等。
猜你喜欢
  • 2017-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多