Brad Brad - 1 year ago 59
JSON Question

How can I only select some JSON objects?

Hi I have a script which parses a local JSON object (at the moment just to display a list).

function generateFamilySelect() {
var implantData = JSON.parse(localStorage.getItem("implantData"));
var implantFamilies = "";
$.each(implantData.implantFamilies, function( index, value ) {
implantFamilies += implantData.implantFamilies[index].familyDisplay + "<br />";

and the JSON object:


At the moment, the list shows all of the elements. How can I modify this script to only show those with

Also, a quick syntax question, I feel like the line

implantFamilies += implantData.implantFamilies[index].familyDisplay + "<br />";

could be written something like

implantFamilies += this[index].familyDisplay + "<br />";

but I can't get that to work...

Answer Source

the_5imian has provided a good answer to your first question, and you have determined the obvious alternate solution, given your current code.

As to your second question (this within jQuery.each()):
Within jQuery.each(), this is the value wrapped as an Object. value is the value of the array element at the current index, not the entire array. In other words, you don't use [index] on value or this within this context to get the current array element. For this code, value and this are the same because value is already an Object.

For what you want, you could just use value (Given that all elements of the array are already Objects, you could use this instead, but using value is a better habit to be in.):

$.each(implantData.implantFamilies, function( index, value ) {
    if (value.loadInitially == "1") {
        implantFamilies += value.familyDisplay + "<br />";
    } else {
        //do nothing

this is the value wrapped as an Object:
The following should show you what the values of value and this are within $.each(array,function(index,value){...});:

var myArray = ['zero','one','two','three','four','five'];

$.each(myArray, function(index,value){
  console.log(index + ' value =',value);
  console.log(index + ' this =',this);  //this is the value wrapped as an Object.
<script src=""></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download