0

I'm trying to write a function that accesses an object inside of an array inside of an object and then push that into an array.

This is the code I have right now:

Javascript

stuff: function (index1, index2) {
    for (var i = 1; i < index1.length; i++) {
        state[index2].push(foodData[index1][i].name);
    }
}

When I run storage.stuff('ingredientsToInclude', 'desired') I get the following error:

Cannot read property 'name' of undefined

However, if I access foodData["ingredientsToInclude"][1].name in the console it returns the correct value.

Not sure the reason for the discrepancy.

5
  • 1
    What is index1? Why are you using its length property as the limit for the for loop? Shouldn't that be fooData[index1].length? Commented Aug 17, 2015 at 19:50
  • 2
    The variable i iterates index1, so you probably want index1[i] somewhere. Try foodData[index1[i]] instead of foodData[index1][i] Commented Aug 17, 2015 at 19:51
  • Can you post a json example? Commented Aug 17, 2015 at 19:53
  • change for (var i = 1; i < index1.length; i++) { to for (var i = 1; i < foodData[index1].length; i++) { Commented Aug 17, 2015 at 19:53
  • @Amit.rk3 - This worked. If you make it an answer I'll mark the question as complete. Commented Aug 17, 2015 at 20:27

1 Answer 1

1

you are looping over string 'ingredientsToInclude' instead of actual array foodData['ingredientsToInclude']. So change for (var i = 1; i < index1.length; i++) { to for (var i = 1; i < foodData[index1].length; i++) {

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

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.