• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Miscellaneous / Loop over an object’s keys and values

Loop over an object’s keys and values

Loop over an object’s keys and values

Sometimes your data structure might be a complex object that contains a bunch of key/value pairs. Iterating over each pair is a little odd at first glance depending on what languages you’re used to but its straightforward once you get used to using the functions of Object.

After you grab the objects keys you can loop through the keys and values at the same time. In this example you have access to each pair using the key and value variables during the loop.

let myObject = { one: 1, two: 2, three: 3 };

Object.keys(myObject).forEach((key, value) => {
  //...do something
  console.log(key, value);
});

There’s also a nice overview of how to loop in JavaScript. This one page site has everything you need to know about JavaScript loops.

Source

https://levelup.gitconnected.com/6-javascript-code-snippets-for-solving-common-problems-33deb6cacef3

Miscellaneous

Related Snippets:

  • Multiple Choice Quiz
  • How to change the value of an object which is inside an array
  • Convert a string to a number
  • How To Append An Object To An Array In JavaScript

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers