Water Cooler v2 Water Cooler v2 - 1 month ago 11
Javascript Question

How to return all properties and their values of an object including iterable ones, custom ones and inherited ones?

So far, I've learnt:

1) the

for
loop, I can use to iterate over indices in an object such as an array that has keys that were numeric indices.

2) the
for..in
loop gives me both iterable and custom properties and inherited properties, too. However, it leaves out properties whose values are undefined.

For e.g.

var array = [ 'Apples', , 'Pear' ];

array.newFn = function () { };
Array.prototype.anotherFn = function() { };
array.foo = bar;

for (var prop in array)
console.log(prop);


will leave out index
1
because its value is
undefined
.

It will, however, iterate over
newFn
,
anotherFn
and
foo
.

3) The
for..of
will do exactly as
for..in
but will iterate only over values instead of keys.

Is there a looping construct that iterates over:


  1. All iterable properties; and

  2. Custom ones; and

  3. Those inerhited from prototypes all the way down?



And iterates over the keys? Once I have the keys, I can get the values.

If there isn't an in-built looping construct, there must be some reflective property on
Object
named
keys
or some such that lets me peek into it?

Answer

The simplest approach would be to set the index to undefined using void. You use can Object.keys() to get the indexes and properties of the array.

var array = [ 'Apples', void 0, 'Pear' ];

array.newFn = function () { };
Array.prototype.anotherFn = function() { };
array.foo = "bar";

var keys = Object.keys(array);
console.log(keys);

for (var prop in array)
  console.log(prop);