How to iterate over Javascript object properties
source link: https://christosploutarchou.com/iterate-over-javascript-object-properties/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to iterate over Javascript object properties
Here some very common tasks how to iterating over an JavaScript object properties
If you have an object, you can’t just iterate it using map()
, forEach()
or a for..of
loop.
You will get the following errors:
const items = { 'date': new Date(), 'number': 2, 'sampleString': 'test' }
map()
function will give you TypeError: items.map is not a function
:
items.map(item => {})
forEach()
function will give you TypeError: items.forEach is not a function
:
items.forEach(item => {})
for..of
will give you TypeError: items is not iterable
:
for (const item of items) {}
So, what can you do to iterate?
for (const item in items) { console.log(item) }
You can also do ti by call Object.entries()
function to generate an array with all its enumerable properties, and loop through that, using any of the above methods:
Object.entries(items).map(item => { console.log(item) }) Object.entries(items).forEach(item => { console.log(item) }) for (const item of Object.entries(items)) { console.log(item) }
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK