2011-08-26 144 views
3

我有对象的像返回JSON对象

objArray = [{"color":"red", "width":5, "price":10}, 
    {"color":"green", "width":4, "price":8}, 
    {"color":"red", "width":7, "price":11}] 

阵列如何可以返回对象的阵列,其中所述颜色为红色以JavaScript或jquery的

+2

迭代并且这些对象添加到新的数组,其中'color'是' “红”'。或者是什么问题? https://developer.mozilla.org/en/JavaScript/Guide/Statements#Loop_Statements(btw。这不是一个JSON对象,它只是一个对象数组)。 –

+0

我说在我的描述中的对象数组... – dardub

+1

那么你的问题是什么关于JSON? –

回答

3
var objArray = [{"color":"red", "width":5, "price":10}, 
    {"color":"green", "width":4, "price":8}, 
    {"color":"red", "width":7, "price":11}] 

var tmp = [] 

$.each(objArray,function(i,val){ 
    if(val.color == 'red') 
    { 
     tmp.push(objArray[i]); 
    } 
}); 

console.log(tmp); 
3

如果“返回”,你的意思是从一个函数返回,那么你可以使用Array.prototype.filter这样的:

return objArray.filter(function(v) { return v.color === 'red'; }); 

如果你只是想将它保存到一个变量,那么它只是大致相同:

var red_array = objArray.filter(function(v) { return v.color === 'red'; }); 

为了弥补旧的浏览器,使用the MDN .filter() shim

if (!Array.prototype.filter) { 
    Array.prototype.filter = function (fun /*, thisp */) { 
     "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 thisp = arguments[1]; 
     for (var i = 0; i < len; i++) { 
      if (i in t) { 
       var val = t[i]; // in case fun mutates this 
       if (fun.call(thisp, val, i, t)) res.push(val); 
      } 
     } 

     return res; 
    }; 
} 

或者,如果你想要的jQuery ,请使用$.map()[docs]方法:

var arr = $.map(objArray, function(v) { if(v.color === 'red') return v; }); 

$.grep()[docs]方法:

var arr = $.grep(objArray, function(v) { return v.color === 'red'; }); 

实例:http://jsbin.com/udawir/edit#javascript,live(改变传递给$.each()阵列来记录得到的颜色值)在阵列上