0

I know (with Lodash or vanilla JS) how to loop generally over an object and get the keys and values. _.forOwn() and _.forEach(), etc.

My question is if there is a way to only loop through the keys in a neat shorthand. In other words, can I simplify this code:

_.forEach(myObject, (value, key) => {
 // do something quick and important that only needs key
)}

I don't need the value, only the key, and so I'm wondering if there's a shorthand to just go through the keys.

Tony Brasunas
  • 4,012
  • 3
  • 39
  • 51
  • Possible Duplicate: https://stackoverflow.com/questions/8763125/get-array-of-objects-keys – Kevin B Nov 03 '17 at 21:53
  • Is `for (const key of Object.keys(myObject)) { /* Do stuff with key */ }` what you're looking for? – CRice Nov 03 '17 at 21:55
  • might depend on the "quick and important that only needs key" – Slai Nov 03 '17 at 22:05
  • @KevinB I don't think it's a duplicate of that one, as I read through that. Just want to iterate over the keys of an object without reference to the values. Creating an array first would, sure, do it, but I'm looking for something quicker. – Tony Brasunas Nov 03 '17 at 22:55
  • @CRice that's getting closer. – Tony Brasunas Nov 03 '17 at 22:56
  • quicker... or shorter/simpler. how is CRice's example any different from what i suggested paired with a loop? (it's identical) – Kevin B Nov 03 '17 at 22:56
  • Looking for shorter/simpler code. Doesn't have to beat native JS in milliseconds. – Tony Brasunas Nov 03 '17 at 22:57
  • Nothing is going to be shorter than what you have. – Kevin B Nov 03 '17 at 22:58
  • So there has to be a reference to the `values`, even if I don't need them? – Tony Brasunas Nov 03 '17 at 22:59
  • Yes, unless you create your own iteration method that does it without. but it's still no shorter if you count the code needed to create said iteration method. that includes anything you could do with a library. – Kevin B Nov 03 '17 at 22:59
  • You can as stated use Object.keys to get an array of keys and loop over that, but... it's probably not much better. – Kevin B Nov 03 '17 at 23:00
  • 1
    The best you could do (afaik) is something like `Object.keys(myObject).forEach(someFunctionThatTakesAKey)`. It's not going to get much shorter than that. But I'm not sure why you'd like to get it so succinct? What about `Object.keys` isn't sufficient for your needs? – CRice Nov 03 '17 at 23:03
  • OK, I'm satisfied then, and I already had the simplest iterative method. I'll mark the answer below as good enough. :-) – Tony Brasunas Nov 03 '17 at 23:51

1 Answers1

3

There's no shorthand to provide keys AND loop over them. You could write your own utility method, but essentially you can use Object.keys or _.keys and then .forEach over those results.

With plain JavaScript, you can achieve this with Object.keys, so no LoDash required.

LoDash provides a _.keys method.

Ahmad Mageed
  • 94,561
  • 19
  • 163
  • 174