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.

Daedalus
  • 7,586
  • 5
  • 36
  • 61
Legeo
  • 784
  • 4
  • 20
  • 44

1 Answers1

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);
  })
};
Hikarunomemory
  • 4,237
  • 2
  • 11
  • 21
  • Hey Hikarunomemory, you are helping me a lot. Thank you for everything. Your answer is right :) – Legeo Sep 01 '18 at 12:52