Search code examples
javascriptarraysobjectprototype

Javascript: How to get the all properties of `prototype` or `__proto__` of an Object or Arrays


As we know Object.keys will return the own properties of an Object or Array, But I need all the properties of Array or Object. If you see below image, all the properties of [].__proto__ and {}.__proto__ are not enumerable.

What is the best way to get the all properties including own and __proto__?

enter image description here

What is the best way to get the all properties including own and __proto__?

I tried the following approach, Not sure whether best approach or not.

Example:

const getAllProperties = ref => {
   const own_properites = Object.keys(ref)
   const proto_properties = Object.keys(Object.getOwnPropertyDescriptors(ref.__proto__))
   return [...own_properites, ...proto_properties]
}

const object = {
   name: 'A'
};

console.log({ objectProps: getAllProperties(object) })

const array = [1,2,3];

console.log({ arrayProps: getAllProperties(array) });


Solution

  • You can shorten it somewhat by using Object.getOwnPropertyNames instead of going through the descriptors first. Also, your current method is getting the Object.keys of the instance, but Object.keys skips non-enumerable properties:

    const obj = {};
    Object.defineProperty(obj, 'foo', { value: 'value' });
    console.log(Object.keys(obj));

    So, use getOwnPropertyNames both for the instance and for the prototype.

    You could also consider using Object.getPrototypeOf, unlike the deprecated __proto__.

    const getAllProperties = ref => [
      ...Object.getOwnPropertyNames(ref),
      ...Object.getOwnPropertyNames(Object.getPrototypeOf(ref)),
    ];
    
    const object = {
       name: 'A'
    };
    
    console.log({ objectProps: getAllProperties(object) })
    
    const array = [1,2,3];
    
    console.log({ arrayProps: getAllProperties(array) });