4

Say we have this:

const v = [1,2,3];
v.foo = 5;

console.log(JSON.stringify(v));

we will get:

'[1,2,3]'

and the 'foo' property on the array will be ignored. However, if we do:

console.log(Object.keys(v));

we will get:

[ '0', '1', '2', 'foo' ]

my question is - how can we get only the standard keys from an array, and ignore any properties that were tacked onto the array?

The only way I know how to do this would be something like:

const keys = Object.keys(v).filter(k => Number.isInteger(parseInt(k)));

is there a better way?

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

3 Answers3

5

You can use

Array.from(v.keys())

where keys returns an iterator over integer indices (not property names!). Notice that in contrast to Object.keys it ignores the sparsity of arrays and produces an index even for holes.

I wonder though why you even have to use Object.keys on an array. An array has indices only, and you can generate them with a simple for (let i=0; i<v.length; i++) loop. Or even with something like Array.from({length: v.length}, (_, i) => i).

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

It is advised to not mess with array keys. V8 does performance evaluation based on array keys and does some pretty nice assumptions which if you modify you will loose all the benefits.

But in case you don't care about performance, than you can create a copy of the array and the engine wont copy custom keys.

Object.keys([...v])

Rosmarine Popcorn
  • 10,761
  • 11
  • 59
  • 89
0

You can use Array.from.

const v = [1,2,3];
v.foo = 5;
const keys = Array.from(v);
console.log(keys);
eag845
  • 1,013
  • 1
  • 11
  • 16
  • I am looking for the keys of the array, not the values. I think I am looking for `Array.prototype.keys()` => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys – Alexander Mills Dec 08 '18 at 22:19