我有这段代码
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']
任何建议非常感谢
答案 0 :(得分:2)
答案 1 :(得分:1)
尝试以下
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;
答案 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' ]