Home > Web Front-end > JS Tutorial > How Can I Access JavaScript Object Property Values Without Knowing the Keys?

How Can I Access JavaScript Object Property Values Without Knowing the Keys?

Linda Hamilton
Release: 2024-12-14 22:03:19
Original
460 people have browsed it

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
    }
}
Copy after login

ECMAScript 5 :

var keys = Object.keys(obj);

for (var i = 0; i < keys.length; i++) {
    var val = obj[keys[i]];
    // Use val
}
Copy after login

ECMAScript 2015 (ES6):

for (const key of Object.keys(obj)) {
    const val = obj[key];
    // Use val
}
Copy after login

ECMAScript 2017 :

const values = Object.values(obj);

// Use values array or:

for (const val of Object.values(obj)) {
    // Use val
}
Copy after login

Object.values Shim for Older Browsers:

Object.values = obj => Object.keys(obj).map(key => obj[key]);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template