2010-01-18 9 views
13

Tengo una matriz de JavaScript como la siguiente, que debo filtrar para obtener los valores secundarios correctos de los datos de prueba a continuación.Filtrar elementos en matriz de JavaScript usando jQuery

var arrChildOptions2 = [ 
     {Parent:'opt1',Value:'opt1',Text:'Parent1 - Child 1'}, 
     {Parent:'opt2',Value:'opt1',Text:'Parent 2 - Child 1'}, 
     {Parent:'opt2',Value:'opt2',Text:'Parent 2 - Child 2'} 
    ]; 

Los valores se utilizan para completar un menú desplegable en función del evento de cambio de un menú desplegable primario como se muestra a continuación.

$(function() { 
    $('#ddl1').change(function() { 
     $('#ddl2 option:gt(0)').remove(); 
     $('#ddl2').addItems('#ddl2', arrChildOptions2[Parent=opt2]); 
    }); 
}); 

donde additems es una función que recorre la matriz. El problema es que no puedo filtrar por padre, he intentado usar contiene y el anterior arrChildOptions2 [Parent = opt2] pero no puedo filtrarlo, preferiría encontrar una buena solución en lugar de utilizar un bucle for? Cualquier idea, aplausos

+0

[ 'array.filter()'] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) – Blazemonger

Respuesta

30

Puede tener más suerte con la función jQuery.grep() en lugar de jugar con bucles.

Esta función "busca los elementos de una matriz que satisfaga una función de filtro. La matriz original no se ve afectada".

+0

Excelente Phil , gracias, no estaba al tanto de esa función, todavía bastante nueva para jquery, funciona de maravilla. – Israfel

2

Sí tratar grep jQuery, así:

arr = jQuery.grep(JSON_ARRAY, index); 
2

array.filter() existe en JavaScript básico:

function isBigEnough(element) { 
    return element >= 10; 
} 
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); 
// filtered is [12, 130, 44] 

Esa página de documentación incluye un polyfill para navegadores antiguos:

if (!Array.prototype.filter) 
{ 
    Array.prototype.filter = function(fun /*, thisArg */) 
    { 
    "use strict"; 

    if (this === void 0 || this === null) 
     throw new TypeError(); 

    var t = Object(this); 
    var len = t.length >>> 0; 
    if (typeof fun !== "function") 
     throw new TypeError(); 

    var res = []; 
    var thisArg = arguments.length >= 2 ? arguments[1] : void 0; 
    for (var i = 0; i < len; i++) 
    { 
     if (i in t) 
     { 
     var val = t[i]; 

     // NOTE: Technically this should Object.defineProperty at 
     //  the next index, as push can be affected by 
     //  properties on Object.prototype and Array.prototype. 
     //  But that method's new, and collisions should be 
     //  rare, so use the more-compatible alternative. 
     if (fun.call(thisArg, val, i, t)) 
      res.push(val); 
     } 
    } 

    return res; 
    }; 
} 
0

Usted podría utilizar la función jQuery.filter() para construir un nuevo jQuery ob objeto de un subconjunto de los elementos coincidentes.

var result = [ 
 
     {Parent:'opt1',Value:'opt1',Text:'Parent1 - Child 1'}, 
 
     {Parent:'opt2',Value:'opt1',Text:'Parent 2 - Child 1'}, 
 
     {Parent:'opt2',Value:'opt2',Text:'Parent 2 - Child 2'} 
 
    ]; 
 
    
 
     
 
var filteredResult = $(result).filter(function(idx) { 
 
    return result[idx].Parent === 'opt2'; 
 
});   
 
    
 
    
 
var options = $("#result-list"); 
 
$.each(filteredResult, function() { 
 
    options.append($("<option />").val(this.Value).text(this.Text)); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<select id="result-list" name="select" title="List"/>

Cuestiones relacionadas