I have an object similar to
var obj = { 'Earth': 1, 'Sky': 2, 'Tree': 3, 'Sand': 4 };
I am trying to filter based on value using this
$.filter(obj,function(i, value){
return value>3;
});
However this is returning empty.
Expected output
{'Sand': 4 }
Is there a way to filter by value, when the indexes of the objects cannot be consistently addressed and may vary.
JavaScript objects don't have a filter() method, you must first turn the object into an array to use array's filter() method. You can use the Object. keys() function to convert the object's keys into an array, and accumulate the filtered keys into a new object using the reduce() function as shown below.
jQuery filter() Method The filter() method returns elements that match a certain criteria. This method lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match will be returned.
JavaScript's Objects are not iterable like arrays or strings, so we can't make use of the filter() method directly on an Object . filter() allows us to iterate through an array and returns only the items of that array that fit certain criteria, into a new array.
The jQuery filter() method can take the selector or a function as its argument to filters the set of matched elements based on a specific criteria.
Try something like this..
function filterObjectProperties(obj, filtercb){
var ret = {};
for(var p in obj)
if(obj.hasOwnProperty(p))
if(filtercb(obj[p]))
ret[p] = obj[p];
return ret;
}
var obj = { 'Earth': 1, 'Sky': 2, 'Tree': 3, 'Sand': 4 };
var newObj = filterObjectProperties(obj, function(val){
return val > 3;
});
https://jsfiddle.net/dht2L55L/
This can be done without $.filter
:
var obj = { 'Earth': 1, 'Sky': 2, 'Tree': 3, 'Sand': 4 };
result = {};
for (var k in obj) {
if (obj[k] > 3) {
result[k] = obj[k];
}
}
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With