![](/img/trans.png)
[英]Performant way of finding unique values of keys from a list of objects in typescript
[英]Correct way to return a list of unique keys from Object
我有這個代碼
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']
任何建議,不勝感激
嘗試跟隨
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' ]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.