Is there a native or library function for checking multiple keys at once?
Say this is my object:
const foo = {};
foo.superLongNameNeededByPackage = {cat: {black: 1}, hat: 2, bat:3, mat: 12}
console.log(foo);
// { superLongNameNeededByPackage : {cat: {black: 1}, hat: 2, bat:3, mat: 12} }
And I want to check that it has various keys on it, if there a way to do this?
const isReadyForHalloween = hasMultipleKeys(foo.superLongNameNeededByPackage,
['cat.black', 'hat', 'bat']);
I’m aware of lodash’s has
as well as the fact I can write my own using Object.keys
and every
but I was hoping to avoid it if possible, becuse it would still feel overly verbose and requires writing out the full formulation.
const arr = Object.keys(foo.superLongNameNeededByPackage);
arr.every(item => item.hasOwnProperty("a")
&& item.hasOwnProperty("b")
&& item.hasOwnProperty("c") );
But I don’t want to be writing out hasOwnProperty
each time, and may want to supply my key list as its own variable.
I had the exact same question a few days ago. This is what I came across. It uses the flat package. https://www.npmjs.com/package/flat
Although lodash doesn’t have a built in function, you can create
hasMultipleKeys()
using_.overArgs()
.The function takes the array of keys, and an object you wish to check. The array is passed directly to
_.every()
(via_.identity()
), while the object is applied to_.has()
(using_.curry()
) to create the predicate for the_.every()
function.Here is my solution:
You could take two functions, one to check the path and another to check if all keys are in the object.