Home >Web Front-end >JS Tutorial >How Can I Access JavaScript Object Property Values Without Knowing the Keys?
Accessing Object Property Values without Knowing Keys
To retrieve property values from a JavaScript object without knowing the keys, consider the following methods:
ECMAScript 3 :
for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var val = obj[key]; // Use val } }
ECMAScript 5 :
var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { var val = obj[keys[i]]; // Use val }
ECMAScript 2015 (ES6):
for (const key of Object.keys(obj)) { const val = obj[key]; // Use val }
ECMAScript 2017 :
const values = Object.values(obj); // Use values array or: for (const val of Object.values(obj)) { // Use val }
Object.values Shim for Older Browsers:
Object.values = obj => Object.keys(obj).map(key => obj[key]);
Choosing the Appropriate Method:
Select the method that best aligns with the browsers you need to support. For browsers supporting ES6 or later, the Object.keys, Object.forEach, and Object.values methods are preferred. In cases where you need to support older IE versions, ES3 solutions are necessary.
The above is the detailed content of How Can I Access JavaScript Object Property Values Without Knowing the Keys?. For more information, please follow other related articles on the PHP Chinese website!