Home > other >  How do I loop through a JavaScript object?
How do I loop through a JavaScript object?

Time:09-25

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

CodePudding user response:

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);
      }

CodePudding user response:

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