• 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:

  • Determine if a string contains a substring
  • Redirect to a specified URL
  • Reverse the order of items in an array
  • Add characters to the end of a string if it’s less than a certain length

Primary Sidebar

FREE UPDATES!

Get the latest updates in your inbox for FREE!

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2023 JavaScriptSource.com

  • About
  • Privacy Policy
  • Submit
  • FAQ
  • Jobs For Developers
  • Contact Us