0

i have an array of object inside another object. when i iterate this array with

t.schedules.forEach(function(item) {
    console.log(item[index]);

});

it shows error Uncaught TypeError: t.schedules.forEach is not a function.

but i am able to get it with t.schedules[index];

please see this image

with index

enter image description here

6
  • Please post more of the code. Where does t get populated with respect to your forEach? Commented Aug 31, 2018 at 5:27
  • What ever schedules is, it is not an array (or you're using a really old IE). Commented Aug 31, 2018 at 5:32
  • t.schedules may not be an array Commented Aug 31, 2018 at 5:33
  • 1
    @Neha If you create object like var a = {1: 'Hello'}; then it will also return Hello with a[1]. But a is object not array. Commented Aug 31, 2018 at 5:55
  • 1
    Log t.schedules not t.schedules[0] so we can see it’s structure. Commented Aug 31, 2018 at 6:01

2 Answers 2

1

Try like this. If t.schedules is an object then Object.values(t.schedules) will return array of values from that object. Then you can use forEach

if (typeof t.schedules == "object") {
    t.schedules = Object.values(t.schedules);
}
t.schedules.forEach(function(item) {
    console.log(item[index]);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! typeof(t.schedules) returns Object
0

This sort of thing often happens if you try iterating before the array is populated. The logged object looks like a database entry judging by the "created_at", "updated_at" etc. keys so I'm guessing you are retrieving the array from a database? If so, check that you are waiting for the response before iterating.

3 Comments

yes array is populated from ajax response
That's a comment and not an answer
An answer shouldn’t be speculative. Are you sure this answer is correct?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.