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

Correct way to return a list of unique keys from Object

本文关键字:方法 列表 一键 Object 返回 唯一      更新时间:2023-09-26

我有这个代码

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

如何返回一个styleId数组,以便获得唯一的值,如'N18', 'N22', 'N50P', 'SA61']

任何建议都非常感谢

您可以从使用_.map_.uniq延迟评估discounts对象开始。

演示

var result = _(discounts)
  .map(function(value, key) {
    return key.split('-')[0];
  })
  .uniq()
  .value();
console.log(result);

尝试以下

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());

我不擅长CoffeeScript,但这里有一个在Javascript 中使用lodash的例子

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

我得到的是这样的:

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' ]