简体   繁体   中英

Accessing an object inside of an array inside of an object in javascript

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.

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++) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM