简体   繁体   中英

When using .each in jQuery with a JSON object how do I avoid undefined properties?

I'm attempting to fill the values of <inputs> on a page using the data from a JSON object.

http://codepen.io/jimmykup/pen/exAip?editors=101

First I create my JSON object. In this case it only has two values. One name and one url .

var jsonObj = [];

var name = "1stname";
var url = "firsturl";

item = {}
item ["name"] = name;
item ["url"] = url;

jsonObj.push(item);

Next I use jQuery's .each() to find all inputs with a class of .name and I use the index to insert the value of "name" into the input. After that I want to go through all of the inputs with .url as the class name and do the same.

$("input.name").each(function( index ) {
    if ( jsonObj[index].name ) {
      $(this).val( jsonObj[index].name );
  }
});

$("input.url").each(function( index ) {
    if ( jsonObj[index].url ) {
      $(this).val( jsonObj[index].url );
  }
});

The problems is that if my JSON object has 1 value for "name" but .each() finds 2 inputs, once it gets to the second input I get this error in my console.

Uncaught TypeError: Cannot read property 'name' of undefined

Then my second .each() function fails to run. What can I do to avoid this issue?

You need to make sure jsonObj[index] is defined before trying to get the name or url .

$("input.name").each(function( index ) {
  var data = jsonObj[index];
  if ( data && data.name ) {
    $(this).val( data.name );
  }
});

$("input.url").each(function( index ) {
  var data = jsonObj[index];
  if ( data && data.url ) {
    $(this).val( data.url );
  }
});

Json objet is in this form::

var jsonobj={"name":"1stname","url":"firsturl"};

with this format you can execute your code.

and what you are forming is basically an array.

Check that the index is less than the length of the array, otherwise quit the loop:

$("input.name").each(function( index ) {
  if (index < jsonObj.length && jsonObj[index].name ) {
    $(this).val( jsonObj[index].name );
  } else {
    return false;
  }
});

$("input.url").each(function( index ) {
  if ( index < jsonObj.length && jsonObj[index].url ) {
    $(this).val( jsonObj[index].name );
  } else {
    return false;
  }
});

Fork

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM