Created
April 27, 2017 02:48
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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