Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • To get all properties that belong to an object in javascript

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 149
    Comment on it

    To get all properties that belong to an object in javascript, we can use Object.getOwnPropertyNames(). The ordering of the non-enumerable properties in the array, and among the enumerable properties, is not defined.

    Example:

    var arr = ['a', 'b', 'c'];
    console.log(Object.getOwnPropertyNames(arr).sort()); // logs '0,1,2,length'
    
    // Array-like object
    var obj = { 0: 'a', 1: 'b', 2: 'c' };
    console.log(Object.getOwnPropertyNames(obj).sort()); // logs '0,1,2'
    
    // Logging property names and values using Array.forEach
    Object.getOwnPropertyNames(obj).forEach(function(val, idx, array) {
      console.log(val + ' ---; ' + obj[val]);
    });
    
    // non-enumerable property
    var myobj = Object.create({}, {
      getFoo: {
        value: function() { return this.foo; },
        enumerable: false
      }
    });
    myobj.foo = 1;
    
    console.log(Object.getOwnPropertyNames(myobj).sort()); 
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: