Filtering a JavaScript Object
I have a Java script that looks something like this in the browser console
https://www.dropbox.com/s/53spm6lf7o6oa8z/Selecci%C3%B3n_2015-07-10-001.png
What I would like to do is return a filtered object based on the content of the "class" property ... I have looked into JQuery.grep () or .filter () but they don't quite work as this object is not an array and I was unable to convert it into one ...
I will appreciate the pointer in the right direction
// object
var obj = your_obj;
var matchedClass = "your_matched_class";
var filteredObj = {};
for (var key in obj) { // iterating over object and checking for class
if (obj.hasOwnProperty(key) && obj[key].class === matchedClass) {
filteredObj[key] = obj[key];
}
}
If you are looking for a tool / framework to do this easily, it looks like you are after lodash
It supports _.filter as well as other handy features that will probably help you with processing. If you can be more specific about your desired output, we can probably help you with a specific answer.
You can iterate over the keys of the objects with:
var keys = Object.keys(myObj)
and then filter the list of keys:
var matchingKeys = keys.filter(function(key) {
return myObj[key].class === 'somevalue')`
}
and then extract those keys from the object.