如何过滤多维javascript数组

时间:2012-02-09 07:24:27

标签: javascript arrays json filter multidimensional-array

这是我的第一篇文章:我一直在寻找解决方案很长一段时间。

所以我有这个JSON数据:

var object = [{
    "nid": "31",
    "0": {
        "tid": "20",
        "name": "Bench Press",
        "objectDate": "2012-02-08",
        "goal": "rep",
        "result": "55.00",
        "comments": "sick!",
        "maxload": "250"
    },
    "1": {
        "tid": "22",
        "name": "Back Squat",
        "objectDate": "2012-02-08",
        "goal": "time",
        "result": "8.00",
        "comments": "i was tired.",
        "maxload": "310"
    }},
{
    "nid": "30",
    "0": {
        "tid": "19",
        "name": "Fran",
        "objectDate": "2012-02-07",
        "goal": "time",
        "result": "5.00",
        "comments": null
    }}];

我想按名称过滤它。例如,如果我为名称“Fran”应用过滤器,我希望有类似的东西:

[0] => Array
     (
        [tid] => 19
        [name] => Fran
        [objectDate] => 2012-02-07
        [goal] => time
        [result] => 5.00
        [comments] => 
     )
[1] => Array
     (
        [tid] => 19
        [name] => Fran
        [objectDate] => 2012-02-08
        [goal] => rep
        [result] => 55.00
        [comments] => woohoo!
     )

有可能实现吗?任何帮助将不胜感激!产品:>

6 个答案:

答案 0 :(得分:10)

在Javascript中没有此功能。你必须自己编写这样的函数。

var arr = [{"nid":"31","0":{"tid":"20","name":"Bench Press","objectDate":"2012-02-08","goal":"rep","result":"55.00","comments":"sick!","maxload":"250"},"1":{"tid":"22","name":"Back Squat","objectDate":"2012-02-08","goal":"time","result":"8.00","comments":"i was tired.","maxload":"310"}},{"nid":"30","0":{"tid":"19","name":"Fran","objectDate":"2012-02-07","goal":"time","result":"5.00","comments":null}}];


function filterByProperty(array, prop, value){
    var filtered = [];
    for(var i = 0; i < array.length; i++){

        var obj = array[i];

        for(var key in obj){
            if(typeof(obj[key] == "object")){
                var item = obj[key];
                if(item[prop] == value){
                    filtered.push(item);
                }
            }
        }

    }    

    return filtered;

}

var byName = filterByProperty(arr, "name", "Fran");
var byGoal = filterByProperty(arr, "goal", "time");

答案 1 :(得分:8)

var result = [];
for (var i = 0; i < object.length; i++)
{
    if (object[i].name == 'Fran')
    {
        result.push(object[i]);
    }
}

答案 2 :(得分:7)

我会创建一个过滤功能

function filter(array, key, value){
    var i, j, hash = [], item;

    for(i =  0, j = array.length; i<j; i++){
        item = array[i];
        if(typeof item[key] !== "undefined" && item[key] === value){
            hash.push(item);
        }
    }

    return hash;
}

更强大的解决方案可能是在原型中添加过滤方法:

    `This prototype is provided by the Mozilla foundation and
     is distributed under the MIT license.
     http://www.ibiblio.org/pub/Linux/LICENSES/mit.license`

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array();
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
      {
        var val = this[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, this))
          res.push(val);
      }
    }

    return res;
  };
}

然后只需致电:

function filterName (item, index, array) {
  return (item.name === "Fran");
}

var result = object.filter(filterName);

答案 3 :(得分:0)

最大的诀窍是制作一个平面阵列,只包含你想要的项目。

说你有一个像这样的二维数组:

e = [[1,2],[1,2],[2,3],[4,5],[6,7]]

你制作了一个新阵列:

var f = []

只用1项填写:

for(var x=0;x<e.length;x++) f[x] = e[x][1]
给我们的喜欢:

f = [2,2,3,5,7]

然后......

var g = e.filter( function(elem, pos){ return (f.indexOf(elem[1]) == pos) })

cowabunga!

答案 4 :(得分:0)

我尝试使用Diode的解决方案。我适应我的情况。包括3个数组。

var arr = 
[

  {
    taskTypeGroupId: "EXP.CONT", taskTypeGroupName: "Contradictoire", 
    taskType: 
    {
      taskTypeId: "DGE-EXPCONT", taskTypeName: "Dégats des eaux contradictoire", defaultDuration: 60, isInProject: false, 
      dataItems:
      {
        id: "EXTRAFILLER5", label: "Divers 5"
      }
    }
  },

  {
  takTypeGroupId: "EXPQUAL", taskTypeGroupName: "Contrôle qualité", 
    taskType: 
    {
      taskTypeId: "DGE-EXPQUAL", taskTypeName: "Contrôle qualité dégats des eaux", defaultDuration: 60, isInProject: false, 
      dataItems: 
      {
        id: "EXTRAFILLER5", label: "Divers 5"
      }
    }
  }

];
function filterByProperty(array, prop, value){
var filtered = [];

for(var i = 0; i < array.length; i++){
var array1 = array[i];
  for(var key in array1){
    if(typeof(array1[key] == "object")){
    var array2 = array1[key];
      for (var key2 in array2){
        if(typeof(array2[key2] == "object")){
        var array3 = array2[key2];
          if(array3[prop] == value){
            filtered.push(array3);
          }
        }
      }
    }
  }
}    
return filtered;

}

JsBin example

答案 5 :(得分:0)

如果您的对象包含3个字段,例如email,firstName,lastName,则可以使用此字段。

ArrayObject
.filter(em => em.email.indexOf(searchEmail) > -1)
.filter(fn => fn.firstName.indexOf(searchFirstName) > -1)
.filter(ln => ln.lastName.indexOf(searchLastName) > -1)