-
Notifications
You must be signed in to change notification settings - Fork 2
Object.keys
The Object.keys()
method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in
loop (the difference being that a for-in
loop enumerates properties in the prototype chain as well).
Object.keys(obj)
obj
The object whose enumerable own properties are to be returned.
Object.keys()
returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. The ordering of the properties is the same as that given by looping over the properties of the object manually.
var arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']
// array like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']
// array like object with random key ordering
var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(an_obj)); // console: ['2', '7', '100']
// getFoo is property which isn't enumerable
var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; } } });
my_obj.foo = 1;
console.log(Object.keys(my_obj)); // console: ['foo']
// Create a constructor function.
function Pasta(grain, width, shape) {
this.grain = grain;
this.width = width;
this.shape = shape;
// Define a method.
this.toString = function () {
return (this.grain + ", " + this.width + ", " + this.shape);
}
}
// Create an object.
var spaghetti = new Pasta("wheat", 0.2, "circle");
// Put the enumerable properties and methods of the object in an array.
var arr = Object.keys(spaghetti);
document.write (arr);
// Output:
// grain,width,shape,toString
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links