Javascript: get object value from Object [closed]

Demo:,js,output (click Run with JS button first)


<!DOCTYPE html>
  <script src=""></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <button type="button" onclick="showRajatMessages()">Show Rajat Messages</button>
  <ul id="result"></ul>


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"){
    } else {
      continue; // skip

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


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.

Browse More Popular Posts

Leave a Comment