revision:
The Object.getOwnPropertyNames() static method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object.
Object.getOwnPropertyNames(obj)
Parameters:
obj : required. The object whose enumerable and non-enumerable properties are to be returned.
const object1 = { a: 1, b: 2, c: 3 }; console.log(Object.getOwnPropertyNames(object1)); // Expected output: Array ["a", "b", "c"]
<div> <p id="name-1"></p> <p id="name-2"></p> <p id="name-3"></p> <p id="name-4"></p> </div> <script> const arr = ["a", "b", "c"]; console.log(Object.getOwnPropertyNames(arr).sort()); // ["0", "1", "2", "length"] document.getElementById("name-1").innerHTML = "property names : " + JSON.stringify(Object.getOwnPropertyNames(arr).sort()); // Array-like object const obj = { 0: "a", 1: "b", 2: "c" }; console.log(Object.getOwnPropertyNames(obj).sort()); // ["0", "1", "2"] document.getElementById("name-2").innerHTML = "property names : " + JSON.stringify(Object.getOwnPropertyNames(obj).sort()); Object.getOwnPropertyNames(obj).forEach((val, idx, array) => { console.log(`${val} -> ${obj[val]}`); document.getElementById("name-3").innerHTML += "property names : " + `${val} -> ${obj[val]}` + "<br>"; }); // 0 -> a // 1 -> b // 2 -> c // non-enumerable property const myObj = Object.create( {}, { getFoo: { value() { return this.foo; }, enumerable: false, }, }, ); myObj.foo = 1; console.log(Object.getOwnPropertyNames(myObj).sort()); // ["foo", "getFoo"] document.getElementById("name-4").innerHTML = "property names : " + Object.getOwnPropertyNames(myObj).sort(); </script>
<div> <p id="name-5"></p> <p id="name-6"></p> <p id="name-7"></p> </div> <script> const nfn = { val1: "ninja1", val2: "ninja2", val3: "ninja3", val4: "ninja4" }; console.log(Object.getOwnPropertyNames(nfn)); document.getElementById("name-5").innerHTML = "property names : " + JSON.stringify(Object.getOwnPropertyNames(nfn)); let nfn2 = { val1: 'ninja1', val2: 'ninja2', val3: 'ninja3' }; console.log(Object.getOwnPropertyNames(nfn2).sort()); document.getElementById("name-6").innerHTML = "property names : " + JSON.stringify(Object.getOwnPropertyNames(nfn2).sort()); Object.getOwnPropertyNames(nfn2). forEach(function (val, idx, array) { console.log(val + ': ' + nfn2[val]); document.getElementById("name-7").innerHTML += val + " : " + nfn2[val] +"<br>"; }); </script>