Obtaining the name of a property in a JavaScript object that contains a hyphen symbol

I'm facing a challenge in my application where I need to extract JSON data. The issue arises when the JSON data retrieved from the service contains dashes ("-"). This leads to an error message saying "Uncaught ReferenceError: person is not defined". For example:

Here is the JSON object:

 var JSONObject ={
 "name-person":"John Johnson",
 "street":"Oslo West 16", 
 "age":33,
 "phone":"555 1234567"};

When I try to access the data using the console log statement below, I encounter the error "Uncaught ReferenceError: person is not defined":

  console.log(JSONObject.name-person);

I am unable to modify the source data coming from the service or database. Can someone suggest a solution to handle this kind of data with dashes in it?

Answer №1

Give this method a try: JSONObject["name-person"]

In JSON, an object consists of key-value pairs where a key can contain any character, including reserved keywords such as for, function, and if. When accessing an item in an object by its key that does not follow the rules for a valid identifier (), you must use square brackets [ ].

Take a look at this humorous example to better understand:

var strangeObject = {" ...this is a TOTALLY valid key!!! ": 123, 
                   "function": "what a weird key..."};

console.log(strangeObject [" ...this is a TOTALLY valid key!!! "], 
            strangeObject ["function"]); 

Answer №2

To retrieve the property, make use of the square bracket syntax.

JSONObject['name-person']

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Positioning divs in CSS can be achieved similarly to how table cells are structured in HTML

Once again today, I came across a familiar issue with CSS layouts. I want to have 5 divs in a horizontal row, each with different widths: 1: 60px, 2: 30%, 3: 40px, 4: *, 5: 100px Back in the day, tables were the way to go for layouts, but now they are c ...

Receive JSON data with camel-case in a Web API 2.0 using a model in pascal-case style

My attempt to execute a PUT call on my Web API involves configuring the WebApiConfig.cs file to send data back to my Web project in camel case format. config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesCont ...

Cannot Properly Import JSX Elements in TailwindCSS and React

I am facing an issue with importing a JSX Element into my main file, App.js. The element I want to load is in a separate file called element.js and contains the following code: const element = () => { return ( <div className="text-gr ...

What could be the reason for the Mongoose findAll function causing a 500 error to occur?

My model / Schema has a working create method, but the "all" method is causing a 500 error. var mongoose = require('mongoose'); var Schema = mongoose.Schema; var DiSchema = new mongoose.Schema({ name: { type: String, lowercase: true , require ...

Ways to retrieve information from a different website's URL?

Having a bit of an issue here. I'm currently browsing through some reports on webpage #1 () and I have a specific requirement to extract the object named "data" from webpage #2 (). However, the code I've used seems to fetch the entire webpage ins ...

Utilize the setInterval method to repeatedly call the random function

Can someone assist me in setting a time interval of about 1 second for this function? function random_imglink(){ var myimages=new Array() //insert your desired random images below myimages[1]="/documents/templates/bilgiteknolojileri/standalo ...

What is the best method for storing a JavaScript widget with analytics - should it be done dynamically or statically?

My widget comes with a customizable boot loader that is used on websites. The boot loader file retrieves the settings for the widget and generates it accordingly. Normally, the content of the bootloader file remains static unless there are modifications ma ...

The date sorting feature in AngularJS is experiencing difficulties

I am currently facing an issue with sorting my JSON data based on the date provided in the object. The sorting functionality seems to only consider the first digits of the date, for example, in "19-08-2017" it only checks "19" and ignores "-08-2017". Here ...

The $scope property is successfully updated in the test browser, but unfortunately, it does not reflect

sample document: describe('$rootScope', function() { describe('$on', function() { var credentials = "Basic abcd1234"; var $scope; var $rootScope; var $httpBackend; ... beforeEach(inje ...

JavaScript counter unexpectedly resetting to zero instead of the specified value

After gathering feedback from voters: My current issue revolves around a Java counter I created. Ideally, the numbers should start at 0 and increment to the specified number upon page load. You can see an example of this functionality here: https://codepe ...

Connecting to a specific slide within a carousel using an array of thumbnails

Utilizing a gallery field from ACF in WordPress, I aim to showcase all images as thumbnails with a Masonry layout. When an image is clicked, it should open a carousel within a modal and navigate directly to the corresponding slide. The code below effectiv ...

How should a JavaScript object be properly formatted?

Recently, I created a project using ng-repeat with AngularJS 1.x, and it was smooth sailing. JavaScript: var app = angular.module('myModule', []); app.controller('myController', function() { this.dishes = [ { 'name&a ...

What's causing my page to not refresh when props are updated? Frustrated React newcomer struggling to figure it out after two days of trying

After completing a few tutorials, I ventured into creating my first React app which is a simple blog site. However, I've been facing a challenge for the past two days and would really appreciate some assistance! The website displays blog posts fetche ...

In Android TextView, the src attribute of a JSON value is being used to display a small blue-colored box

After successfully retrieving a JSON value to display in an Android TextView, I encountered an issue with the formatting. Here is the sample JSON Value: "introtext": "The District Administration Office has sealed the case was underway.&lt;img src= ...

What methods can be used to defer the visibility of a block in HTML?

Is there a way to reveal a block of text (h4) after a delay once the page has finished loading? Would it be necessary to utilize setTimeout for this purpose? ...

Tips for preserving my cookies and URLs in a text file

I'm facing an issue with logging my Cookies and URL. I am able to log them, but I am struggling to set them to variables. Can someone please assist me with this? When I try to set both of them to variables, all I get in return is Promise { } driver ...

a function that is not returning a boolean value, but rather returning

There seems to be a simple thing I'm missing here, but for the life of me, I can't figure out why the function below is returning undefined. var isOrphanEan = function isOrphanEan (ean) { Products.findOne({ 'ean': ean }, func ...

Eradicate white space in a JavaScript code

Calling all JS programmers! Here's a challenge for you, check out this demo: https://codepen.io/gschier/pen/jkivt I'm looking to tweak 'The pen is simple.' to be 'The pen issimple.' by removing the extra space after 'is& ...

How can we use a base-class to deserialize Json into a generic entity in C#?

I am looking for a way to easily convert JSON objects to entity classes without having to write redundant code multiple times. That's why I created a base class for my entities and now I want to deserialize them without knowing which specific derived- ...

Push the accordion tab upwards towards the top of the browser

I am working on an accordion menu that contains lengthy content. To improve user experience, I want to implement a slide effect when the accordion content is opened. Currently, when the first two menu items are opened, the content of the last item is disp ...