基于其他属性查询多维数组属性

Query a multidimensional array property based on other properties

本文关键字:属性 查询 数组 于其他 其他      更新时间:2023-09-26

这是场景...

我有以下多维数组:

[
    [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}