如何过滤多维 JavaScript 数组

Posted

技术标签:

【中文标题】如何过滤多维 JavaScript 数组【英文标题】:How to filter multidimensional JavaScript array 【发布时间】:2012-03-01 16:34:29 【问题描述】:

我有这些数据:

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!
     )

有没有可能实现?

【问题讨论】:

您可能对我的 JSON.search API 感兴趣,它比 $.grep 快 5 倍,并允许您使用正则表达式进行搜索。见json.spiritway.co mathjs.org/docs/reference/functions/filter.html 【参考方案1】:

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");

【讨论】:

【参考方案2】:

问题是关于多维数组。如果你像我一样错过了这里是普通数组的解决方案......

2020

filteredArray = array.filter(item => item.name.indexOf('Fran') > -1);

filteredArray = array.filter(function(item)

    return item.name.indexOf('Fran') > -1);

2012版

var result = [];
for (var i = 0; i < array.length; i++)

    if (array[i].name === 'Fran')
    
        result.push(array[i]);
    

【讨论】:

这是旧的但黄金 @CyrilleConMorales 好吧,我今天不会这样做。首先我会使用===,但使用Array.filter会更好 为什么我不能使用 Array.filter 而是第二种解决方案?当我使用第一个解决方案时,它给了我一个语法错误。【参考方案3】:

我会创建一个过滤函数

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

【讨论】:

【参考方案4】:

如果您的对象包含 3 个字段,例如电子邮件、名字、姓氏,那么您使用它。

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

【讨论】:

【参考方案5】:

最大的诀窍是制作一个包含您想要的项目的平面数组。

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

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!

【讨论】:

【参考方案6】:

我尝试了 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

【讨论】:

以上是关于如何过滤多维 JavaScript 数组的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Javascript 中创建多维数组? [复制]

通过(例如:标题或描述)值中的关键字过滤多维数组(PHP)

如何拆分 JavaScript 多维数组并获取最后一个数组?

javascript自己实现多维数组遍历

如何在javascript中对多维数组进行排序

如果javascript中不存在值,如何推送到多维数组