Javascript:过滤二维数组

时间:2010-12-12 19:25:44

标签: javascript arrays sorting filter

有很多关于如何根据它的数值对javascript数组进行排序的例子。但是,如果使用属性myArrayprop1获取所有元素并使用其值value1,那么从哪个方面获取适当的方法是什么?

这是我的数组:

var myArray = [
{
    "id":"2",
    "name":"My name",
    "properties":{"prop1":"value1"}
}];

由于

4 个答案:

答案 0 :(得分:2)

您可以通过点或括号表示法访问它,并将匹配的成员推送到新的/已过滤的数组,例如:

var newArray = [];
for(var i=0, l = myArray.length; i<l; i++) {
  if(myArray[i].properties.prop1 == "value1") newArray.push(myArray[i]);
}

您的问题有点含糊不清,如果您尝试获取{"prop1":"value1"}对象而不是父对象,则只需将newArray.push(myArray[i])更改为newArray.push(myArray[i].properties)

答案 1 :(得分:1)

提供比较函数以按任意属性排序:

function compareMyObjects(a, b) {
  var valA = a.properties.prop1.value1;
  var valB = b.properties.prop1.value1;

  if(valA > valB) return 1;
  if(valA < valB) return -1;
  return 0;
}

myArray.sort(compareMyObjects);

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort

答案 2 :(得分:0)

浏览数组中的每个元素。对于每个元素,请检查每个属性以查看它是否与您要查找的属性匹配。

function filterArray(array, property, value) {
    var newArray = [];
    for (var i = 0; i < array.length; i++) {
        for (var j in array[i].properties) {
            if (j === property && array[i].properties.hasOwnProperty(j)) {
                if (array[i].properties[j] == value) {
                    newArray.push(array[i]);
                }
            }
        }
    }
}

答案 3 :(得分:0)

var newarray=myarray.filter(function(itm){
   return itm.properties.prop1==='value1';
});

过滤器,就像数组方法indexOf和map一样,可能值得为没有它的浏览器提供 - 这个版本来自Mozilla开发者网站 -

if(!Array.prototype.filter){
    Array.prototype.filter= function(fun, scope){
        var L= this.length, A= [], i= 0, val;
        if(typeof fun== 'function'){
            while(i< L){
                if(i in this){
                    val= this[i];
                    if(fun.call(scope, val, i, this)){
                        A[A.length]= val;
                    }
                }
                ++i;
            }
        }
        return A;
    }
}
相关问题