2012-02-09 32 views
8

Esta es mi primera publicación: he estado buscando una solución durante bastante tiempo.Cómo filtrar matriz javascript multidimensional

Así que tienen estos datos 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 
    }}]; 

y me gustaría filtrar por su nombre. Por ejemplo, si aplico un filtro para el nombre de "Fran", me gustaría tener algo como esto:

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

¿Es posible lograr? ¡Cualquier ayuda sería muy apreciada! :>

+0

Puede que le interese mi API JSON.search que es 5 veces más rápida que $ .grep y le permite buscar utilizando expresiones regulares. Consulte http://json.spiritway.co/ – mgwhitfield

Respuesta

8

No hay función para esto en Javascript. Tienes que escribir tu propia función así.

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

gracias! Tuve que pasar por otro nivel, pero funciona ahora :) – davidgmar

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

me gustaría crear una función para filtrar:

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

Una solución más robusta podría ser la adición de un método de filtro para el prototipo:

`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; 
    }; 
} 

Luego simplemente llame al:

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

var result = object.filter(filterName); 
+1

+1 para la función 'filter' – diEcho

0

El gran truco consiste en hacer una matriz plana con solo el elemento que desee.

que usted tiene una matriz 2D de este modo:

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

se crea una nueva matriz:

var f = [] 

llenarlo con sólo 1 punto:

for(var x=0;x<e.length;x++) f[x] = e[x][1] 

nosotros el dar Me gusta de:

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

y luego ....

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

cowabunga!

Cuestiones relacionadas