Javascript: get object value from Object [closed]

Demo: http://jsbin.com/gaxalupuka/edit?html,js,output (click Run with JS button first)

HTML:

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <button type="button" onclick="showRajatMessages()">Show Rajat Messages</button>
  <ul id="result"></ul>
</body>
</html>

JS:

var data = [
             {name: 'Rajat',
              messages: [
                          {id: 1, message: 'Hello'},
                          {id: 3, message: 'Hello 2'}
                        ]
             },
             {name: 'Himesh',
              messages: [
                          {id: 2,message: 'Hello'}
                        ]
             },
             {name: 'David',
              messages: [
                          {id: 4,message: 'Hello'}
                        ]
             },
              {name: 'Rajat',
              messages: [
                          {id: 1, message: 'Hello 3'},
                          {id: 3, message: 'Hello 4'}
                        ]
             }
            ];


function showRajatMessages() {
  for (i = 0; i < data.length; i++) { 
    if(data[i].name == "Rajat"){
      showMessages(i);
    } else {
      continue; // skip
    }
  }
}

function showMessages(i) {
  console.log(i);
  var messages = data[i].messages;
  for (j = 0; j < messages.length; j++) {
   $("#result").append("<li>" + messages[j].message + "</li>"); 
  }
}

Explanation:

First, we listen for the button click. This button click will run showRajatMessages() function.

Inside showRajatMessages() function, we loop thru the data. If the node has name that equal to Rajat, we’re going to call showMessages() function and pass the object position inside the data array as i.

Inside the showMessages() function, we have access to the i that just passed from the showRajatMessages() function.

So inside here, we find the right object from the data array and grab the messages key.

And for each item inside the messages key, we’ll add the message as <li> and push the <li> into the <ul> with id name result inside the HTML using jQuery .append() method.

Leave a Comment