HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptModerate

Quickly filter an object by keys

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
quicklyobjectfilterkeys

Problem

I am trying to optimize an object filter function. Given an array of keys, I need to filter an object. I feel that creating a new object each time may degrade performance. Is there a way to mock the Array.prototype.filter function for objects?



function main() {
var Types = {
INTEGER: { value: 'int' },
CHARACTER: { value: 'char' },
FLOAT: { value: 'float' },
DOUBLE : { value: 'double' },
STRING: { value: 'str' },
BOOLEAN: { value: 'bool' }
};

var Numbers = filterByKeys(Types, [ 'INTEGER', 'FLOAT', 'DOUBLE' ]);

console.log(Numbers);
};

function listToSet(list) {
var _set = {};
if (Ext.isArray(list)) {
for (var i = 0; i
.as-console-wrapper { top: 0; max-height: 100% !important; }




Without ExtJS Dependency



function main() {
var Types = {
INTEGER: { value: 'int' },
CHARACTER: { value: 'char' },
FLOAT: { value: 'float' },
DOUBLE : { value: 'double' },
STRING: { value: 'str' },
BOOLEAN: { value: 'bool' }
};

var Numbers = filterByKeys(Types, [ 'INTEGER', 'FLOAT', 'DOUBLE' ]);

console.log(Numbers);
};

function listToSet(list) {
var _set = {};
if (isArr(list)) {
for (var i = 0; i
.as-console-wrapper { top: 0; max-height: 100% !important; }
``

Solution


  • Use var myKeys = Object.keys(myObject) to get the keys.



-
Check if a myString exist in the array myKeys using native

var matchingKey = myKeys.indexOf(myString) !== -1


Processing an array? Use this:

var matchingKeys = myKeys.filter(function(key){ return key.indexOf(myString) !== -1 });


-
Get the value using myObject[matchingKey].

Processing an array? Use this:

var matchingValues = matchingKeys .map(function(key){ return myObject[key] });


-
No need to check array-boundaries or sizes. It's 100% boundary-safe.

Code Snippets

var matchingKey = myKeys.indexOf(myString) !== -1
var matchingKeys = myKeys.filter(function(key){ return key.indexOf(myString) !== -1 });
var matchingValues = matchingKeys .map(function(key){ return myObject[key] });

Context

StackExchange Code Review Q#79384, answer score: 14

Revisions (0)

No revisions yet.