Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery filter object by value with inconsistent index

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.

like image 623
Joel Avatar asked Apr 11 '16 14:04

Joel


People also ask

How do you filter objects with keys?

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.

How do we filter out elements using jQuery?

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.

Can we apply filter on object in JavaScript?

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.

Which type of parameter can jQuery filter function take?

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.


2 Answers

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/

like image 84
I wrestled a bear once. Avatar answered Nov 11 '22 14:11

I wrestled a bear once.


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);
like image 2
u_mulder Avatar answered Nov 11 '22 14:11

u_mulder