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
3 Answers 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);
Comments
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)
Comments
Short & Simple:
let objArray = [ {"color":"red", "width":5, "price":10},
{"color":"green", "width":4, "price":8},
{"color":"red", "width":7, "price":11} ]
let newRedArray = objArray.filter(item => item.color === "red");
Hope it helps!
coloris"red". Or what's the problem? developer.mozilla.org/en/JavaScript/Guide/… (btw. this is not a JSON object, it's just an array of objects).