C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
JavaScript Object.getOwnPropertyNames() MethodThe Object.getOwnPropertyNames() method returns an array of all properties (except those non-enumerable properties which use symbol) found directly upon a given object. Syntax:Object.getOwnPropertyNames(obj) Parameter:obj: It is the object whose enumerable and non-enumerable own properties are to be returned. Return value:This method returns an array of string that correspond to the properties found directly upon the object. Browser Support:
Example 1const object1 = { a: 0, b: 1, c: 2, }; console.log(Object.getOwnPropertyNames(object1)); Output: ["a", "b", "c"] Example 2var 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]); }); Output: ["0", "1", "2"] "0 -> a" "1 -> b" "2 -> c" Example 3function Pasta(grain, size, shape) { this.grain = grain; this.size = size; this.shape = shape; } var spaghetti = new Pasta("wheat", 2, "circle"); var names = Object.getOwnPropertyNames(spaghetti).filter(CheckKey); document.write(names); // Check whether the first character of a string is 's'. function CheckKey(value) { var firstChar = value.substr(0, 1); if (firstChar.toLowerCase() == 's') return true; else return false; } Output: size,shape
Next TopicJavaScript Objects
|