0

i would like to display only details of Linda using JSON. However, I am clueless on how to do it. Need some advice, thanks!

The output should show the updated table with only "Linda" instead of my current output.

Actual question: Using JSON, modify the mobile of Linda to 88885555, and display only the details of Linda.

My employees object is supposed to be from .json file but i couldnt find the format to insert into this post. Hence, i combined it into my .js file.

var employees = [
  {
    "Name": "Tony",
    "Mobile": 99221111,
    "Email": "tony@json.com"
  },
  {
    "Name": "Linda",
    "Mobile": 98981111,
    "Email": "linda@json.com"
  },
  {
    "Name": "Patrick",
    "Email": "patrick@json.com"
  },
  {
    "Name": "Isabella",
    "Mobile": 99552222
  }
];

employees[1].Mobile = 88885555;

function buildHtmlTable() {
  var columns = addAllColumnHeaders(employees);

  for (var i = 0; i < employees.length; i++) {
    var row$ = $('<tr/>');
    
    for (var colIndex = 0; colIndex < columns.length; colIndex++) {
      var cellValue = employees[i][columns[colIndex]];

      if (cellValue == null) {
        cellValue = "";
      }

      row$.append($('<td/>').html(cellValue));
    }
    
    $("#employeeTable").append(row$);
  }
}

// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(employees) {
  var columnSet = [];
  var headerTr$ = $('<tr/>');

  for (var i = 0; i < employees.length; i++) {
    var rowHash = employees[i];
    
    for (var key in rowHash) {
      if ($.inArray(key, columnSet) == -1) {
        columnSet.push(key);
        headerTr$.append($('<th/>').html(key));
      }
    }
  }
  
  $("#employeeTable").append(headerTr$);

  return columnSet;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body onLoad="buildHtmlTable()">
  <table id="employeeTable" border="1"></table>
</body>
MTCoster
  • 5,868
  • 3
  • 28
  • 49
Janice
  • 13
  • 3
  • What do you mean by _"display"_? At which point during the process? Initially, or based on user action? – guest271314 Feb 11 '19 at 16:00
  • Hi, it means that the updated table should be displayed instead of the current output. – Janice Feb 11 '19 at 16:03
  • Should the `` be populated first, and then only display the row containing _"Linda"_? Or, only the populate the `
    ` with values corresponding to data associated with _"Linda"_?
    – guest271314 Feb 11 '19 at 16:05
  • The first option, populate everything but only display row containing "Linda" – Janice Feb 11 '19 at 16:07
  • At what point during the process? Immediately? – guest271314 Feb 11 '19 at 16:07
  • yes, immediately – Janice Feb 11 '19 at 16:09
  • You can use conditional statement inside for loop, then use continue to skip unwanted employees. I.e if(employee.name !== "Linda") continue; if you need detail explanation, let me know. I should fetch my pc – Edwin Dijas Chiwona Feb 11 '19 at 16:12
  • should i do the "if else" inside the .json file or .js file? – Janice Feb 11 '19 at 16:18
  • A .json file is just data. .js, a JavaScript file, is where you would write programming code/logic. – Andy G Feb 11 '19 at 16:22
  • pro tip: `==` should NOT be used in javascript. It can cause unintended type coersion. Instead, use `===`: https://stackoverflow.com/a/359509 – random_user_name Feb 11 '19 at 16:22
  • 1
    Possible duplicate of [Javascript find json value](https://stackoverflow.com/questions/19253753/javascript-find-json-value) – random_user_name Feb 11 '19 at 16:24
  • Sounds like you would want to do a `find` for the record where `name: === 'Linda'`, then display that single record. I'd suggest checking out this question and answers: https://stackoverflow.com/q/19253753 – random_user_name Feb 11 '19 at 16:24

2 Answers2

0

You can create a function that accepts an "employee name", .not() and .is() to match any <td> elements within the <tr> where .textContent is equal to the argument passed to the function, chain .hide() to set the display of the matched elements to "none".

To display all <tr> elements you can use $("#employeeTable tr").show().

Substituted using jQuery(function(){}) for onload attribute event handler at <body> element.

var employees = [{
    "Name": "Tony",
    "Mobile": 99221111,
    "Email": "tony@json.com"
  },
  {
    "Name": "Linda",
    "Mobile": 98981111,
    "Email": "linda@json.com"
  },
  {
    "Name": "Patrick",
    "Email": "patrick@json.com"
  },
  {
    "Name": "Isabella",
    "Mobile": 99552222
  }
];


employees[1].Mobile = 88885555;

function buildHtmlTable() {
  var columns = addAllColumnHeaders(employees);

  for (var i = 0; i < employees.length; i++) {
    var row$ = $('<tr/>');
    for (var colIndex = 0; colIndex < columns.length; colIndex++) {
      var cellValue = employees[i][columns[colIndex]];

      if (cellValue == null) {
        cellValue = "";
      }

      row$.append($('<td/>').html(cellValue));
    }
    $("#employeeTable").append(row$);
  }
}

// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(employees) {
  var columnSet = [];
  var headerTr$ = $('<tr/>');

  for (var i = 0; i < employees.length; i++) {
    var rowHash = employees[i];
    for (var key in rowHash) {
      if ($.inArray(key, columnSet) == -1) {
        columnSet.push(key);
        headerTr$.append($('<th/>').html(key));
      }
    }
  }
  $("#employeeTable").append(headerTr$);

  return columnSet;
}
<!DOCTYPE html>
<html>

<head>
  <title>Task 1</title>

  <!-- using of jquery, calling external js file -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
  <table id="employeeTable" border="1">
  </table>
  <script>
    $(function() {

      buildHtmlTable();

      function hideRow(employeeName) {
        return $("#employeeTable tr").not(function(index, element) {
          return $(element.cells).is(function(i, el) {
            return el.textContent === employeeName
          });
        }).hide();
      }
  
      hideRow("Linda");

    });
  </script>
</body>

</html>
guest271314
  • 1
  • 15
  • 104
  • 177
  • Nice answer. I think you should also address the use of `==`, for example `cellValue == null`. Also, it's worth pointing out that in some javascript projects, `variable$` indicates an observable. It's my understanding that to indicate a jQuery object, best practice is `$variable`.... – random_user_name Feb 11 '19 at 16:26
  • @cale_b Do not concur with the `$` prefix at variables associated with jQuery objects. They are just variables. Your comment to OP at https://stackoverflow.com/questions/54634343/how-do-i-display-only-details-of-linda-using-json/54634861#comment96061844_54634343 should be sufficient to illustrate the difference between `==` and `===`. Though can include a note in the answer concerning the differences. – guest271314 Feb 11 '19 at 16:28
  • Fair enough, but my point is only that they are conventions that have meaning: https://stackoverflow.com/questions/37671700/angular2-style-guide-property-with-dollar-sign and https://stackoverflow.com/questions/3360858/why-use-dollar-sign-in-the-name-of-javascript-variables - your answer, do what you want. – random_user_name Feb 11 '19 at 16:33
  • @cale_b _"Can you point to a reference that states that this is a jQuery convention?"_ https://stackoverflow.com/questions/3360858/why-use-dollar-sign-in-the-name-of-javascript-variables#comment3490420_3360883 – guest271314 Feb 11 '19 at 16:38
  • 1
    No authoritative reference, no. But there is lots of "community" authored references. – random_user_name Feb 11 '19 at 17:37
0

If I understood your question correctly you could do something like I did below. I used setTimeout so you can see the transition from your original output to the updated output:

function buildTable(arr) {
  let html = "<table border='1' style='width: 100%'>";
  for (let i = 0; i < arr.length; i++) {
    html += `<tr>
      <td>${arr[i].Name   || ''}</td>
      <td>${arr[i].Mobile || ''}</td>
      <td>${arr[i].Email  || ''}</td>
    </tr>`;
  }
  html += "</table>";
  return html;
}

function init() {
  const LINDA_IDX = 1;
  container.innerHTML = buildTable(employees);
  setTimeout(function() { //
    //Update Linda's phone number
    employees[LINDA_IDX].Mobile = 88885555;
    //Show just Linda in the table
    container.innerHTML = buildTable([employees[LINDA_IDX]])
  }, 2000);
}

var employees = [{
  "Name": "Tony",
  "Mobile": 99221111,
  "Email": "tony@json.com"
}, {
  "Name": "Linda",
  "Mobile": 98981111,
  "Email": "linda@json.com"
}, {
  "Name": "Patrick",
  "Email": "patrick@json.com"
}, {
  "Name": "Isabella",
  "Mobile": 99552222
}];

var container = document.querySelector('#container');

init();
After 2 seconds setTimeout will execute showing Linda's updated info:<br />
<div id="container"></div>
Tom O.
  • 5,730
  • 2
  • 21
  • 35