基于其他属性查询多维数组属性
Query a multidimensional array property based on other properties
这是场景...
我有以下多维数组:
[
[1, 'red', 'x', true],
[1, 'red', 'y', true],
[1, 'red', 'z', false],
[2, 'red', 'x', true],
[2, 'red', 'y', false],
[2, 'red', 'z', false],
[1, 'blue', 'x', true],
[1, 'blue', 'y', true],
[1, 'blue', 'z', false],
[2, 'blue', 'x', true],
[2, 'blue', 'y', true],
[2, 'blue', 'z', false]
]
用户可以选择前三个属性中的任何两个,我需要为其余数组返回 true 或 false 列表。
例如,如果用户选择"blue"和"x",我会返回:1:true,2:true。
可能并不总是有 3 个选项,可能更多或少则一个。
有人对此有优雅的解决方案吗?
过滤器将非常优雅地执行此操作:
var data = […];
var selected = [ , 'blue', 'x', ]; // could be any two
// note the sparse array!
var result = data.filter(function(item) {
return selected.every(function(v, i) {
return item[i] == v;
});
}); // [[1,"blue","x",true],
// [2,"blue","x",true]]
如果要将该列表作为对象,请使用
var key = [0, 1, 2].filter(function(k){ return ! (k in selected); })[0];
var obj = result.reduce(function(m, item) {
m[item[key]] = item[3];
return m;
}, {}); // {"1":true,"2":true}
我做了一个函数 女巫把结果放到一个数组中,这是代码笔
function getMatch(b,c){
var found = 0;
for(var i = 0; i<a.length;i++){
found = 0;
for(var j = 0; j<4; j++){
if(a[i][j] == b){
found += 1;
}
if(a[i][j] == c){
found += 1;
}
if(found == 2){
found = 0;
match.push(a[i]);
}
}
}
}
我做了一个小函数来超级轻松地搜索数据数组,您所要做的就是为数据定义一个映射。
函数:(JSFiddle)
function findInData(data, map, query) {
var matches = [];
data.forEach(function (value) {
var match = true,
result = {};
for (var property in query) {
if (query.hasOwnProperty(property)) {
if (value[map[property]] !== query[property]) {
match = false;
}
}
}
if (match) {
result[value[0]] = value[map['result']];
matches.push(result);
}
});
return matches;
}
示例地图(用于您的数据):
var map = {
color: 1,
XYZ: 2,
result: 3
}
color: 1
因为颜色的值位于数据数组的[1]
位置
示例用法:
var example = findInData(data, map, {color: 'blue', XYZ: 'x'})
返回
{"1":true}
{"2":true}
相关文章:
- 新手查询动态添加属性
- 根据jquery数据属性值进行查询
- select2:无法读取null的属性查询
- 基于其他属性查询多维数组属性
- j查询在设置属性后在后续单击时不读取数据属性
- 使用 SharePoint 查询字符串值作为应用程序部件属性
- MEAN.js MongoDB查询中用户特定计算的属性
- 动态添加数据时按数据属性查询JQuery选择器
- 查询css类的属性值,即使不在使用中
- 追加并替换data-*属性URL的查询字符串值
- 类型错误:无法读取未定义的 mysql 查询的属性“名称”
- 无法向 Mongoose 查询返回的对象添加新属性
- j查询不显眼的验证属性参考
- j查询使用 [] 选择名称属性
- 通过 Javascript 从 href 属性获取查询字符串
- j查询验证引擎属性不起作用
- 如何在索引数据库中按属性查询对象
- j根据特定对象属性查询唯一对象
- 类型错误:试图将未定义的属性查询包装为函数
- Extjs5:如何通过各种属性查询组件