Search code examples
javascriptfor-in-loop

How can i get specific values from array use for in loop


Hello i have the following array:

var data = [
    {
        title: "title 1",
        data2: [
            "content",
        ]
    },
    {
        title: "title 1",
        data2: [
            "content",
        ]
    }
];

how can i get title & data2 values in loop ?

Thanks so much.

edit:

The problem has beed solved with the help of a cat @Niklas Higi but,

how can i get values to my html template in .append function :

<div class="data">
    <div class="data-item">
        <h6>'+data.title+'</h6>
        <ul>
            <li>contents from data2 value</li>
        </ul>
    <div>
<div>

i need get data2 values to li tags.


Solution

  • for(let item of data) {
      console.log(item.title);
      console.log(item.data2);
    }
    

    Please note that I have used for of and not for in as your tag suggested. for in iterates over the indices (in case of an array 0, 1, ...) while for of iterates over the items (Object's in your case).


    Answer to your edit: In the for loop create the elements that you need with document.createElement() and add them to your .data container using .appendChild(). For the <ul> you can just create another for of loop to go over the list items and add them to a <ul> tag you created with document.createElement().