Home > Web Front-end > JS Tutorial > How Do I Iterate Through JavaScript Objects to Access Keys and Values?

How Do I Iterate Through JavaScript Objects to Access Keys and Values?

Mary-Kate Olsen
Release: 2024-12-21 16:59:10
Original
504 people have browsed it

How Do I Iterate Through JavaScript Objects to Access Keys and Values?

Looping Through JavaScript Objects: Iterating over Keys and Values

Retrieving elements from a JavaScript object requires a structured approach to access keys and corresponding values. Consider the example object:

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};
Copy after login

To loop through all elements, leverage the for-in loop:

for (var key in p) {
    // Access the value using the current key
    var value = p[key];
}
Copy after login

However, using for-in may loop through properties inherited from the prototype. To ensure only direct properties are considered, include an additional check:

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        // Access the value using the current key
        var value = p[key];
    }
}
Copy after login

This approach guarantees that only object-specific keys are iterated over, effectively extracting key-value pairs:

"p1" -> "value1"
"p2" -> "value2"
"p3" -> "value3"
Copy after login

The above is the detailed content of How Do I Iterate Through JavaScript Objects to Access Keys and Values?. 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