从Object返回唯一键列表的正确方法
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
如何返回一个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' ]
相关文章:
- 在Javascript中,当使用array.prush方法向列表中添加项目时,如何对其进行排序
- 什么'是从对象列表中一次编辑一个对象的正确Angular/Firebase方法
- 在带有参数列表的表单submit上调用一个方法
- 从填充了 AJAX 的下拉列表中获取控制器的操作方法中的值
- 如何将对象列表传递到MVC4中的控制器方法
- 什么'这是ES6中制作重复元素列表的等效方法
- javascript:更改应用到的数组的数组方法列表
- 未捕获的类型错误:对象#<节点列表>没有方法'addEventListener'
- jQuery验证插件-比较两个选择下拉列表的自定义方法
- 来自Jquery的“.on”方法在动态生成的下拉列表后不起作用
- 有没有一种方法可以在使用html脚本的同时将列表实现为按钮函数
- 有没有一种方法可以在没有jQuery的情况下获得JavaScript中当前添加到后台的事件列表
- 调用.ajax方法得到未定义的json结果,返回json格式列表<字符串>
- 如何将带有数组列表的$(“form”).serialize()从AJAX方法传递到mvc控制器
- 如何使用ajax调用获取数组列表数据(将数组列表数据控制器传递给ajax方法)
- 级联下拉列表mvc3,create方法
- 在调用方法来填充详细信息网格之前,如何从填充的下拉列表中获取信息
- 如何获取 javascript 类中的静态方法列表
- finddomnode(组件)方法列表
- 串行端口没有方法“列表”