从Object返回唯一键列表的正确方法

时间:2015-12-08 17:56:30

标签: javascript coffeescript lodash

我有这段代码

discounts = { 'N18-AB0': 10,
  'N18-AB2': 10,
  'N18-BL2': 10,
  'N22-WHBL0': 10,
  'N22-WHBL1': 10,
  'N22-WHBL2': 10,
  'N22-WHBL3': 10,
  'N50P-CT2': 10,
  'N50P-CT4': 10,
  'SA61-MBL': 10,
  'SA61-MGR': 10,
  'SA61-MHE': 10,
  'SA61-MMB': 10,
  'SA61-MNA': 10,
  'SA61-MPL': 10 }

然后我使用lowdash来提取键值

specials = (req, res, next) ->
  Promise.props
    discounts: discounts
  .then (result) ->
    StyleIds = []
    if result.discounts isnt null
      discounts = result.discounts
      StyleIds = _.forOwn discounts, (value, key) ->
        styleId = key.split(/-/)[0]
        styleId

如何返回一个styleIds数组,以便获得'N18', 'N22', 'N50P', 'SA61']

等唯一值

任何建议非常感谢

4 个答案:

答案 0 :(得分:2)

您可以使用 lazy evaluating _.map < _.uniq DEMO 开始/强>

<强> {{3}}

discounts

答案 1 :(得分:1)

尝试以下

&#13;
&#13;
var discounts = { 'N18-AB0': 10,
  'N18-AB2': 10,
  'N18-BL2': 10,
  'N22-WHBL0': 10,
  'N22-WHBL1': 10,
  'N22-WHBL2': 10,
  'N22-WHBL3': 10,
  'N50P-CT2': 10,
  'N50P-CT4': 10,
  'SA61-MBL': 10,
  'SA61-MGR': 10,
  'SA61-MHE': 10,
  'SA61-MMB': 10,
  'SA61-MNA': 10,
  'SA61-MPL': 10 };

Array.prototype.getUnique = function(){
   var u = {}, a = [];
   for(var i = 0, l = this.length; i < l; ++i){
      if(u.hasOwnProperty(this[i])) {
         continue;
      }
      a.push(this[i]);
      u[this[i]] = 1;
   }
   return a;
}
/* 1. Get keys array
 * 2. Split keys and get value before -
 * 3. Return unique values in an array. */
console.log(Object.keys(discounts).map(function(item){ return item.split("-")[0]}).getUnique());
&#13;
&#13;
&#13;

答案 2 :(得分:0)

我对CoffeeScript不太满意,但这是一个在Javascript中使用lodash的例子

function getUniqueStyleIds(obj) {
    return _.chain(obj)
        .keys()
        .map(function(key) { return key.split('-')[0]; })
        .uniq()
        .value();
}

答案 3 :(得分:0)

我得到了这样的话:

specials = (req, res, next) ->
  Promise.props
    discounts: discounts
  .then (result) ->
    if result.discounts isnt null
      discounts = result.discounts
      styles = _(result.discounts)
        .keys()
        .flatten()
        .map( (c) -> c.split(/-/)[0] )
        .unique()
        .value()

然后样式返回[ 'N18', 'N22', 'N50P', 'SA61' ]