Joel
Joel

Reputation: 1690

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.

Upvotes: 14

Views: 2214

Answers (6)

smnbbrv
smnbbrv

Reputation: 24581

Should be as simple as

var obj = { 'Earth': 1, 'Sky': 2, 'Tree': 3, 'Sand': 4 };

var result = Object.keys(obj)
    .filter(function(e) { return obj[e] > 3 })
    .reduce(function(object, property) { 
         return (object[property] = obj[property], object);
     }, {})

without any library

Upvotes: 1

Alvaro Silvino
Alvaro Silvino

Reputation: 9753

There is no native filter to the Object object, but how about this:

var obj = { 'Earth': 1, 'Sky': 2, 'Tree': 3, 'Sand': 4 };
newObject = {}
Object.keys(obj).map(function(value, index) {
    if (obj[value]>3){
       newObject[value] = obj [value]
    }
});
snippet.log(newObject);
// => {'Sand': 4 }
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Upvotes: 1

Rob Brander
Rob Brander

Reputation: 3781

var obj = { 'Earth': 1, 'Sky': 2, 'Tree': 3, 'Sand': 4 };

function filterObj(obj, valueThreshold) {
  var keys = Object.keys(obj);
  var result = {};
  keys.forEach(function(key) {
    var value = obj[key];
    if (value > valueThreshold) {
      result[key] = value;
    }
  })
  return result;
}

console.log('obj: ' + JSON.stringify(obj));
var filteredObj = filterObj(obj, 3);
console.log('filterdObj: ' + JSON.stringify(filteredObj));

Upvotes: 0

dquinonez
dquinonez

Reputation: 123

You could you JQuery.each(). To use JQuery.filter and JQuery.grep, I think your object should be formed different.

$(function(){

var obj = { 'Earth': 1, 'Sky': 2, 'Tree': 3, 'Sand': 4 };

var result = null;

$.each(obj, function(key, value) {
   if(value > 3){
   result = key;
   }
}); 

console.log(result);

});

Upvotes: 1

u_mulder
u_mulder

Reputation: 54796

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);

Upvotes: 2

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23389

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/

Upvotes: 6

Related Questions