0

PROBLEM

How to iterate through an array of objects?

PEN

Codepen: penHere

CODE

I declared this global const:

const items=[
    {
        name: "axe",
        image: "https://image.ibb.co/cjtHPe/if_weapon_04_707486.png",
        hit: 3
    },

    {   
        name: "redPotion", 
        image: "https://image.ibb.co/gTmU4e/if_18_Harry_Potter_Colour_Potion_Bottle_2730331.png",
        health: 40
    },

];

with this function I gave to characters and items random coordinates where to spawn

function placeCharAndItem(char, items){

    let coord = randomCoord();

    let toCheck = mapA[coord.row][coord.cell];     
    let check = toCheck.search('nonWalkable');


    while(check != -1){
        coord = randomCoord();

        toCheck = mapA[coord.row][coord.cell];     
        check= toCheck.search('nonWalkable');
    };
        place(coord, char);
        placeItem(coord, items);
};

and with the function below the items should be spawn in the map:

function placeItem(coord, items){
  items.forEach(function(obj){
       console.log(items.name);
    coord=randomCoord();  
    var charImage = $("<img>").attr("src", items.image).addClass('items');
    var row = $($("#tableGame tr")[coord.row]);
    var cell = $($("td", row)[coord.cell]);
    var tile = $(".tile", cell);  tile.prepend(charImage);
    })
};

The main problem is that the arrays is iterating(i think) but everytime it gives me " undefined" instead of give me the proper link to the images.

TASK

I've to show the image of these items in a table

Considerations

I read several of your answers about this topic in Stack Overflow, they recommended to use forEach or and old-fashon for loops, I hope I'm correct about this, but if I'm in the wrong way any kind of correction would be really appreciated.

1 Answer 1

2

You're iterating the array but not accessing the object correctly.

function placeItem(coord, items){
  items.forEach(function(obj){ // <- obj is what you want
    // console.log(items.name); <- items is the array
    console.log(obj.name);

    coord=randomCoord();

    // var charImage = $("<img>").attr("src", items.image).addClass('items');
    var charImage = $("<img>").attr("src", obj.image).addClass('items');

    var row = $($("#tableGame tr")[coord.row]);
    var cell = $($("td", row)[coord.cell]);
    var tile = $(".tile", cell);  
    tile.prepend(charImage);
  })
};
Sign up to request clarification or add additional context in comments.

1 Comment

Hey Hikarunomemory, you are helping me a lot. Thank you for everything. Your answer is right :)

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.