How To Use Object Methods in JavaScript
<span class="hljs-comment">// Initialize an object with properties and methods</span> <span class="hljs-keyword">const</span> job = { position: <span class="hljs-string">'cashier'</span>, type: <span class="hljs-string">'hourly'</span>, isAvailable: <span class="hljs-literal">true</span>, showDetails() { <span class="hljs-keyword">const</span> accepting = <span class="hljs-keyword">this</span>.isAvailable ? <span class="hljs-string">'is accepting applications'</span> : <span class="hljs-string">"is not currently accepting applications"</span>; console.log(`The ${<span class="hljs-keyword">this</span>.position} position is ${<span class="hljs-keyword">this</span>.type} and ${accepting}.`); } }; <span class="hljs-comment">// Use Object.create to pass properties</span> <span class="hljs-keyword">const</span> barista = <span class="hljs-built_in">Object</span>.create(job); barista.position = <span class="hljs-string">"barista"</span>; barista.showDetails();
Object.keys()
Object.keys()
creates an array containing the keys of an object.We can create an object and print the array of keys.
<span class="hljs-comment">// Initialize an object</span> <span class="hljs-keyword">const</span> employees = { boss: <span class="hljs-string">'Michael'</span>, secretary: <span class="hljs-string">'Pam'</span>, sales: <span class="hljs-string">'Jim'</span>, accountant: <span class="hljs-string">'Oscar'</span> }; <span class="hljs-comment">// Get the keys of the object</span> <span class="hljs-keyword">const</span> keys = <span class="hljs-built_in">Object</span>.keys(employees); console.log(keys);
Output["boss", "secretary", "sales", "accountant"]
Object.keys
can be used to iterate through the keys and values of an object.<span class="hljs-comment">// Iterate through the keys</span> <span class="hljs-built_in">Object</span>.keys(employees).forEach(key => { <span class="hljs-keyword">let</span> value = employees[key]; console.log(`${key}: ${value}`); });
Outputboss: Michael secretary: Pam sales: Jim accountant: Oscar