Accessing (n)th key from an object
Augusto Moura
augusto.borgesm at gmail.com
Tue Apr 24 16:58:00 UTC 2018
Assuming `Object.keys` has the same order as a simple `for..in` (as stated
in mdn)[
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys],
we can already implement a function to build a iterator from object keys,
and then we can destruct or use others helpers to minimize the array
creation. Something like:
``` js
function* keysIterator(obj) {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
yield key;
}
}
}
const obj = { foo: 12, bar: 89 };
// Using destructuring
const [firstProp, secondProp, ...othersKeys] = keysIterator(obj);
// Using some helper functions
const props = take(2, 10)(obj);
```
The discussion IMHO is if we need that as a built in helper (maybe
`Object.keysIterator()`), and if we need to extend it to `Object.values`
and `Object.entries`.
Em ter, 24 de abr de 2018 às 10:54, somonek <somonek at gmail.com> escreveu:
> Hi all,
>
> Assuming that
>
> const myObject = {
> one: 123,
> two: 456,
> };
>
> could
> myObject[in 0] === 'one' // true
>
> be a better alternative of
> Object.keys(myObject)[0]
>
> and
> myObject[in 3] === undefined
>
> without the need to convert all the object keys into an array, but
> directly accessing one.
>
> Best,
> Serghei
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
--
Augusto Moura
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20180424/95d2c45e/attachment-0001.html>
More information about the es-discuss
mailing list