1

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
2
  • Did you mean for (var m of messages) ? Commented Sep 25, 2021 at 0:27
  • when I use "of" I get Type 'Messages' is not an array type or a string type. Commented Sep 25, 2021 at 0:37

2 Answers 2

1

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);
      }
Sign up to request clarification or add additional context in comments.

3 Comments

When I use of I get "Type 'Messages' is not an array type or a string type."
What does console.log(typeof messages) give you? If it's an object the first option should still work.
yes the first one works. just wondering why the 2nd one doesnt
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.