根据其他属性查询多维数组属性

时间:2015-03-16 16:07:23

标签: javascript arrays

这是场景......

我有以下多维数组:

[
    [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个选项,可能会有更多或者只有一个。

有人有一个优雅的解决方案吗?

3 个答案:

答案 0 :(得分:2)

filter非常优雅地做到这一点:

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}

答案 1 :(得分:0)

我做了一个函数,把结果放到一个数组中,这里是code pen

 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]);
      }
    }    
  }
}

答案 2 :(得分:0)

我做了一个小功能,可以轻松搜索超级数据,您只需要为数据定义一个地图。

功能:(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}
相关问题