Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return json object

I have an array of objects like

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

how can I return an array of objects where the color is red in javascript or jquery

like image 593
dardub Avatar asked Feb 23 '26 07:02

dardub


2 Answers

 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);
like image 73
AlienWebguy Avatar answered Feb 25 '26 20:02

AlienWebguy


If by "return", you mean return from a function, then you can use Array.prototype.filter like this:

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

If you just wanted to save it to a variable, then it's just about the same:

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

To cover for older browsers, use 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;
    };
}

Or if you want jQuery, use the $.map()[docs] method :

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

or the $.grep()[docs] method :

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

Examples: http://jsbin.com/udawir/edit#javascript,live (change the Array passed to $.each() to log the resulting color values)

like image 26
user113716 Avatar answered Feb 25 '26 21:02

user113716