Skip to content

Instantly share code, notes, and snippets.

@lqt0223
Created April 27, 2017 02:48
Show Gist options
  • Save lqt0223/ac2350ac533b95c2f8e5530aad791e25 to your computer and use it in GitHub Desktop.
Save lqt0223/ac2350ac533b95c2f8e5530aad791e25 to your computer and use it in GitHub Desktop.
22 Filter an object and return key-value pairs that pass the filter
function filterObject(obj, fn){
return Object.keys(obj).filter((key) => {
var e = obj[key];
return fn(e);
}).map((e) => {
return {
key: e,
value: obj[e]
};
});
}
var obj = {
a:1,
b:2,
c:{
d:4
}
}
// test
var result = filterObject(obj, (e) => {
return e.d == 4;
});
console.log(result);
// result: [ { key: 'c', value: { d: 4 } } ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment