0

I'm tying to access a specific value in an object array, but ONLY if

a) a specific user ID value is stored in response.feed.data

b) the key story exists

I've been playing around with $.each loops but I'm still sort of confused about accessing values inside nested objects, I'm doing SOMETHING wrong because the value is coming back as undefined no matter how I try to access it, [index].story currently just logs the same array of objects stored in response.feed.data

$.each(response.feed.data, function(key, index){
  if([index].id == "USER ID"){
    if([index].story){
        console.log([index].story);
    }

}
1
  • 1
    try if($(this).id ==="USER ID") what exactly is [index]? I doesn't look right... Commented Oct 23, 2016 at 1:04

2 Answers 2

1

index will store the position of that specific key inside response.feed.data. So you can't access index.story. Instead you will have to access it from key if its present inside key.

Sign up to request clarification or add additional context in comments.

2 Comments

That makes sense. So if I'm understanding correctly, to Iterate through an array inside an object I would require another each loop nested inside the above one, correct?
Using $.each you are iterating through the array response.feed.data. If you have an array within response.feed.data,then you will have to use nested each loop.
0

in $each loop, 1st parameter is your index and 2nd parameter is your element.

so you can access your element like below in your example

$.each(response.feed.data, function(key, index){
  if(index.id == "USER ID"){
    if(index.story){
        console.log(index.story);
    }

}

but follow the best practice and try to put meaning full name. so instead of index you can use item or element as a variable name.

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.