Javascript: Looping through Keys/Values of an Object
The examples below show you how to loop through keys/values of a given object in Javascript.
Example 1: Using Object.entries()
The entries() method returns an array of a given object. It’s supported in all modern browsers and Node.js 7+.
// Kindacode.com
const obj = {
key1: "value 1",
key2: "value 2",
key3: "value 3",
key4: "value 4",
};
// Using forEach
console.log('Using forEach:');
Object.entries(obj).forEach(([key, value]) => {
console.log(`Key: ${key}, Value: ${value}`);
});
// Using map()
console.log('Using map():');
Object.entries(obj).map(([key, value]) => {
console.log(`Key: ${key}, Value: ${value}`);
});
// Using for ... of
console.log('Using for ... of:');
for (const [key, value] of Object.entries(obj)) {
console.log(`Key: ${key}, Value: ${value}`);
}
Output:
Using forEach:
Key: key1, Value: value 1
Key: key2, Value: value 2
Key: key3, Value: value 3
Key: key4, Value: value 4
Using map():
Key: key1, Value: value 1
Key: key2, Value: value 2
Key: key3, Value: value 3
Key: key4, Value: value 4
Using for ... of:
Key: key1, Value: value 1
Key: key2, Value: value 2
Key: key3, Value: value 3
Key: key4, Value: value 4
Example 2: Using Object.keys()
The code:
// Kindacode.com
const obj = {
'color1': 'Blue',
'color2': 'Red',
'color3': 'Orange'
};
for (let key of Object.keys(obj)) {
console.log(`Key: ${key}, Value: ${obj[key]}`);
}
Output:
Key: color1, Value: Blue
Key: color2, Value: Red
Key: color3, Value: Orange
Final Words
We’ve explored some common techniques that can be used to iterate through keys/values of an object. If you’d like to learn more about vanilla Javascript and TypeScript, take a look at the following articles:
- Javascript: Set HTML lang attribute programmatically
- Javascript: 5 ways to create a new array from an old array
- Javascript: Display float with 2 decimal places (3 examples)
- TypeScript Example: Default Function Parameters
- TypeScript: Intersection Type Examples
You can also check out our TypeScript category page for the latest tutorials and examples.
Subscribe
0 Comments