Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript/jQuery, how to retrieve data that has spaces in its name?

I am retrieving JSON using jQuery's getJSON call.

My problem is that some of the fields in the returned JSON have spaces in them.

How do I retrieve these values from the JSON without changing the source data? See line marked "ERROR" below:

$.getJSON(url, null, function(objData) {
  $.each(objData.data, function(i, item) {
    var zip = item.Zip;
    var fname = item.First Name; //ERROR
  });
});

Example JSON:

jsonp123456789({"data":[{"Zip":"12345","First Name":"Bob"},{"Zip":"23456","First Name":"Joe"},{"Zip":"34567","First Name":"Bill"}]})

Thanks

like image 211
frankadelic Avatar asked Dec 07 '09 23:12

frankadelic


People also ask

How to remove space from text in jQuery?

The $. trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string.

How to remove blank space in jQuery?

Answer: Use the jQuery $. trim() function You can use the jQuery $. trim() function to remove all the spaces (including non-breaking spaces), newlines, and tabs from the beginning and end of the specified string.

What is the function of jQuery?

The jQuery library makes it easy to manipulate a page of HTML after it's displayed by the browser. It also provides tools that help you listen for a user to interact with your page, tools that help you create animations in your page, and tools that let you communicate with a server without reloading the page.


1 Answers

Array member access notation works on objects as well.

$.getJSON(url, null, function(objData) {
  $.each(objData.data, function(i, item) {
    var zip = item.Zip;
    var fname = item['First Name'];
  });
});

You can use this for arbitrary strings (those that aren't legal identifiers) as well as variables.

var fieldName = "First Name";
var fname = item[fieldName];
like image 139
Justin Johnson Avatar answered Oct 11 '22 14:10

Justin Johnson