Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
How do I loop through a JavaScript object?

I'm trying to loop through this object and modify some values however I'm getting just the key when I log it.

this.restProviderService.getMessages(this.gameService.getStepId(), this.gameService.teamId).subscribe(messages => {
      console.log(messages);
      for (var m in messages) {
        console.log(m);
      }
      
    });

console.log(messages)

[
    {
        "id": "3",
        "chatId": "1_1",
        "user_id": "21",
        "userName": "batman",
        "msg": "banananananana",
        "createdAt": "1632507755"
    },
    {
        "id": "2",
        "chatId": "1_1",
        "user_id": "31",
        "userName": "jennyg",
        "msg": "asdfasdfasdf",
        "createdAt": "1632507721"
    }
]

Console.log(m)

0
1
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

A for in loop in JS gives you the key. What you do is

      for (var m in messages) {
        var message = messages[m];
        console.log(message);
      }

or

      for (var m of messages) {
        console.log(m);
      }
about 4 years ago · Juan Pablo Isaza Report

0

You are looking for a for...of loop.

In Javascript, a for...in loop will return the index each iteration. (0, 1, so on)

A for...of loop will return the item at each sequential index.

      for (var m of messages) {
        console.log(m);
        //Will log each item in the array in order
      }

You could also use the array method forEach:

messages.forEach((m, index) => {
    console.log(m); // Will print each object
    console.log(index); // 0, 1, 2
});

Relevant MDN

You may also be having trouble because you are dealing with an "array-like object", which can be returned from some methods. Here are some ways to convert it to a usual array. But, TLDR:

 let typicalArray = [...messages];
//Do stuff with typicalArray
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!