Skip to main content

How to Get an Object Keys and Values in JavaScript

how-to-get-object-keys-and-values-in-javascript


Question: How to Get an Object Keys and Values in JavaScript

Answer:

Javascript object

const MyObj = { name: 'RustcodeWeb', mail: 'rustcode95@gmail.com', website: 'www.rustcodeweb.com' }; 


First Method

for (var k in MyObj){ if (MyObj.hasOwnProperty(k)) { console.log("Key: " + k + ", value: " + MyObj[k]); } } 


Second Method

for (const [key, value] of Object.entries(MyObj)) { console.log("Key: " + key + ", value: " + value); } 


Output:

 Key: name, value: RustcodeWeb Key: mail, value: rustcode95@gmail.com Key: website, value: www.rustcodeweb.com 


But if you want to extract 'values' or 'keys' separately, then follow the below method:

extract keys

console.log(Object.keys(MyObj)); 

Output:

["name", "mail", "website"] 


extract values

console.log(Object.values(MyObj)); 

Output:

["RustcodeWeb", "rustcode95@gmail.com", "www.rustcodeweb.com"] 


We try to provide you the best content, if there is any mistake in this article or there is any mistake in code, then let us know.

Comments