0

I have an object video for the view of my node.js app which contains the following.

{ title: 
       [ 'Jason Fried: Why work doesn\'t happen at work',
         'John Maeda: How art, technology and design inform creative leaders',
         'From Storytelling to Storylistening: John Maeda (Future of StoryTelling 2014)' ],
      url: 
       [ 'https://www.youtube.com/watch?v=5XD2kNopsUs&feature=youtu.be',
         'http://www.youtube.com/watch?v=WAuDCOl9qrk&feature=youtu.be',
         'http://www.youtube.com/watch?v=U8-Q70gV2Yk&feature=youtu.be' ] }

I'm trying to loop through these keys and print all the values but I'm not sure if my approach is on the right track. Because I get nothing printed.

<% for (var i = 0; i < video.length; i++) { 

    var videoAtr = video[i]; 

    for (var key in videoAtr) { %>
    <li>
        <%= video[i][key] %>
    </li>
    <% }
} %>

UPDATE

I'd like to print like the following way.

  • title[0] url[0]
  • title[1] url[1]
  • title[2] url[2]
  • 5
    • 2
      An associative array in JavaScript is nothing but an object. Look up how to loop through an object Commented Oct 13, 2015 at 12:42
    • Well, what do you want/expect to be displayed? Commented Oct 13, 2015 at 12:43
    • try video.title.length and video.title[i] Commented Oct 13, 2015 at 12:43
    • you can use this for (var i = 0; i < video.length; i++) { console.log("key and value" + video[i]["Key"], video[i]["Value"]); } Commented Oct 13, 2015 at 12:50
    • Please see the update on my question that I described how I need them displayed. Commented Oct 13, 2015 at 12:54

    1 Answer 1

    2

    As associative arrays are objects in JavaScript you can do this

    for (var key in p) {
       if (p.hasOwnProperty(key)) {
         console.log(key + " -> " + p[key]);
      }
     }
    

    The if condition is to check if the property comes from the prototype which will not be needed as your object stands above


    The reason your code doesn't work is because since it is an object, it doesn't store a length property


    EDIT

    To get the <li> to show

    <% for (var i = 0; i < video.length; i++) { %>
        <li>
        <%for (var key in video) { %>
            <%= video[key][i] %>
        <% }%>
        </li>
    <% } %>
    
    Sign up to request clarification or add additional context in comments.

    3 Comments

    Thanks. I'm getting all the values now but I would like to print them in groups like this <li>title[0] url[0]</li><li>title[1] url[1]</li><li>title[2] url[2]</li> How do I achieve that?
    try to render list in loop
    @SeongLee. I don't know if this is too late but I updated the answer

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.