How can I iterate through the properties of a JavaScript object

0 votes
Can you tell me How I can iterate through the properties of a JavaScript object?
Jan 9 in Java-Script by Ashutosh
• 14,020 points
53 views

1 answer to this question.

0 votes

You can iterate through the properties of a JavaScript object using the following methods:

1. Using Object.keys():

Retrieves an array of keys, which can be iterated using forEach or loops.

Example:

const person = { name: 'Ram', age: 26, city: 'Pune' };

Object.keys(person).forEach(key => {

  console.log(`${key}: ${person[key]}`);

});

Output:

name: Ram

age: 26

city: Pune

2. Using Object.entries() (Key-Value Pairs):

Returns an array of key-value pairs, which is useful for direct iteration.

Example:

const person = { name: 'Priya', age: 22, city: 'Delhi' };

Object.entries(person).forEach(([key, value]) => {

  console.log(`${key}: ${value}`);

});

Output:

name: Priya

age: 22

city: Delhi

answered Jan 10 by Navya

Related Questions In Java-Script

0 votes
1 answer

How to list the properties of a JavaScript object?

Hii @kartik, Use Reflect.ownKeys(): var obj = {a: 1, b: ...READ MORE

answered Jun 8, 2020 in Java-Script by Niroj
• 82,840 points
1,061 views
0 votes
0 answers
0 votes
1 answer

How can I display a JavaScript object?

Hello @kartik, Use native JSON.stringify method. Works with nested objects ...READ MORE

answered Aug 28, 2020 in Java-Script by Niroj
• 82,840 points
591 views
0 votes
1 answer

How can I make a div stick to the top of the screen once it's been scrolled to?

Hello @kartik, Using javascript: var initTopPosition= $('#myElementToStick').offset().top; ...READ MORE

answered Sep 4, 2020 in Java-Script by Niroj
• 82,840 points
874 views
0 votes
1 answer
0 votes
1 answer

How can I configure lazy loading for Angular modules?

To configure lazy loading in Angular, you ...READ MORE

answered Dec 12, 2024 in Angular by Navya
56 views
0 votes
1 answer
0 votes
1 answer

How to sum the values of a javascript object

Certainly, I'd be happy to help you ...READ MORE

answered Sep 25, 2023 in Java-Script by Edureka
• 12,690 points
4,480 views
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP