Exploring ways to display a JavaScript object on click from a .json file

As I delve into the world of javascript and json, I find myself facing a challenge.

I am looking to extract information (using the Get Information function) from a json file within a javascript function triggered by an event. The catch is, I want to accomplish this without relying on jquery or any other library. However, I seem to be hitting a roadblock in my code implementation. Do I need to set up a Request and handle the callback? Or perhaps import additional javascript to properly utilize json data? At this point, all I'm getting is undefined. Any assistance would be greatly appreciated.

The content of the json file:

"hotels": [
    {
        "name": "Hotel Sunny Palms",
        "imgUrl": "imgs/sunny.jpg",
        "rating": 5,
        "price": 108.00
    },
    {
        "name": "Hotel Snowy Mountains",
        "imgUrl": "imgs/snowy.jpg",
        "rating": 4,
        "price": 120.00
    },
    {
        "name": "Hotel Windy Sails",
        "imgUrl": "imgs/windy.jpg",
        "rating": 3,
        "price": 110.00
    },
    {
        "name": "Hotel Middle of Nowhere",
        "imgUrl": "imgs/nowhere.jpg",
        "rating": 4,
        "price": 199.00
    }
]

Here is a snippet of my javascript:

function hot1(){
var text = '{"hotels": [{"name": "Hotel Sunny Palms","imgUrl": "http://www.pruebaswebludiana.xyz/imgs/sunny.jpg","rating": 5,"price": 108.00}]}';
var obj = JSON.parse(text);
document.getElementById("img-container").innerHTML =
obj.imagUrl+ "<br>"+ obj.name+ " " +obj.rating+ " " +obj.price;}

In addition, here is my HTML code snippet:

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2" />
  <link rel='stylesheet' href='style.css' type='text/css' media='all' />

</head>
<body>
<nav></nav>
<div class="container">
    <div>
        <ul>
            <li onclick="hot1()">Hotel Sunny Palms</li>
            <li onclick="hot2()">Hotel Snowy Mountains</li>
            <li onclick="hot3()">Hotel Windy Sails</li>
        <li onclick="hot4()">Hotel Middle Of Nowhere</li>
    </ul>
</div>
<div class="banner-section" id="img-container">
</div>


</body>
</html>

Answer №1

Make sure to check your JSON file for an array in the property hotels. You will need to access this array to work with the data. Here is an example of how you can do that:

var jsonData = ...;
var parsedData = JSON.parse(jsonData);
var hotelsArray = parsedData.hotels;
var targetHotel = hotelsArray[0]; // Change the index number to access different hotels
document.getElementById("img-container").innerHTML = 
    targetHotel.imgUrl + "<br/>" + targetHotel.name + " " + targetHotel.rating + " " + targetHotel.price;

Answer №2

{"hotels": [{"name": "Hotel Sunny Palms","imgUrl": "http://www.pruebaswebludiana.xyz/imgs/sunny.jpg","rating": 5,"price": 108.00}]}

The reason you are receiving an undefined message is because you are attempting to retrieve the name (and other attributes) from the main object.

This primary object does not contain those specific attributes. It only holds one attribute: hotels.

The value of the hotels attribute is an array.

Within that array lies an object.

The attributes you seek belong to that particular object within the array.

For example:

obj.hotels[0].name // etc

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

Transform [object HTMLDocument] to a String

Could someone guide me in converting the newHTMLDocument object into a full string including the doctype and html tag? let newHTMLDocument = document.implementation.createHTMLDocument(); let html = `<!DOCTYPE html> <html> <head> ...

Problem with YouTube iFrame API in IE when using JavaScript

Apologies for the unclear heading, but I'm facing a peculiar issue. The YouTube iFrame API works perfectly on all browsers except Internet Explorer. In IE, none of the JavaScript code runs initially. However, when I open DevTools and refresh the page, ...

Creating a harmonious relationship between a generator using recursion and promises

In Elasticsearch, it's feasible to make a "Scrolling" request. This method involves keeping a cursor open and retrieving large chunks of data gradually. Demo code is available for reference. The provided code uses callbacks and recursion to fetch dat ...

Implementing Knockout.js with JqueryUI Autocomplete: Access the complete object instead of just the value

I have implemented a custom binding for a JQueryUI auto complete feature that works well. However, I am looking to modify it so that it returns the Item object, which can then be pushed to another array. Can someone provide guidance on how to achieve this ...

"Facing a dilemma with Javascript's Facebox getElementById function - not fetching any

Utilizing facebox, I am initiating a small modal dialog with a form and attempting to retrieve the value from a text field on that form using javascript. Below is the HTML code: <div id="dialog-form95" style="display:none"> <div class="block"> ...

Implementing an All-Routes-Except-One CanActivate guard in Angular2

In order to group routes within a module, I am aware that it can be done like this: canActivate: [AuthGuard], children: [ { path: '', children: [ { path: 'crises', component: ManageCrisesComponent }, ...

Difficulty displaying response from Ajax request in Zend Framework

I am encountering an issue with Zend Ajax. Here is my JavaScript code: function deleteNewsCategory(cId) { var conf = confirm("Are you sure you want to delete the item?"); if(conf) { $.ajax({ dataType: 'json', url: '/aja ...

I seem to be stuck in an endless loop within React and can't find a way to break free

Currently, I am utilizing the useState() function along with an array errors[] as part of the state and a function setError() to pass the useState() function to child elements for calling purposes: const [errors, setErrors] = useState([]); //-------------- ...

Transforming a string into an array containing objects

Can you help me understand how to transform a string into an array of objects? let str = `<%-found%>`; let result = []; JSON.parse(`["${str}"]`.replace(/},{/g, `}","{`)).forEach((e) => ...

Tips for showcasing varied information on Morris Chart

I am working with a Morris chart that is populated with a collection of data, each item containing 6 different data values. My goal is to switch between displaying two different sets of data. For example, I want to show the 'Target' data always ...

Transition smoothly with a fade effect when switching between models

I am in the process of creating a basic query system. While I can display questions one at a time, I am looking to incorporate transitions when switching between questions. To further illustrate my issue, I have set up a Plunker demonstration: http://plnk ...

Material UI - The array is unexpectedly resetting to contain 0 elements following an onChange event triggered by the TextField component

As I work on developing an application, one of the key features involves allowing users to select others from a list with whom they can create a group chatroom. Additionally, there is a TextField where they can assign a name to their newly created group. ...

Guide in activating popup notification upon form submission in React with the help of React Router navigate hook

I'm facing a challenge in triggering a success pop-up notification after submitting a form in React. The issue arises when the page redirects to a different location using React Router's useNavigate() hook, as there is no direct connection betwee ...

Learn how to subscribe to Azure Event Grid using Angular without the need for a backend service layer

I am currently working on an Angular project and I am looking to set up Azure Event Grid subscription directly from the client-side without the need for a backend service. After exploring different options, I have not yet found a straightforward solution. ...

Converting JSON data into an array using JavaScript

Stored in a variable named "response", I have the JSON value below: {"rsuccess":true,"errorMessage":" ","ec":null,"responseList":[{"id":2,"description":"user1"},{"id":1,"description”:"user2"}]} var users=response.responseList; var l = users.length; H ...

Service Worker Tips: Caching the initial page with dynamic content

I have a single-page application with a dynamic URL generated using a token, for example: example.com/XV252GTH, which includes various assets such as CSS and favicon. This is how I implement the Service Worker registration: navigator.serviceWorker.regist ...

Error: The 'current' property is not defined and cannot be focused on

I have a total of 4 input fields, and I would like the user to automatically move to the next input field after filling out the current one. constructor(props) { ... this.textInput1 = React.createRef(); this.textInput2 = React.createRef(); ...

The 'import' statement is not functioning properly within a script in the rendered HTML

While working on an express application, I've encountered a recurring error that I can't seem to solve. The error message is: "GET http://localhost:3000/javascript/module2 net::ERR_ABORTED 404 (Not Found)" Could someone kindly assist me in ident ...

Encountered an issue during my initial AJAX call

Hello everyone, I am currently attempting to use AJAX to send a request with a button trigger and display the response HTML file in a span area. However, I am encountering some issues and need help troubleshooting. Here is my code snippet: //ajax.php < ...

The layout in Nextjs _app does not stay constant; it refreshes with each page change

After creating a _app.js file: const MyApp = ({Component, pageProps}) => { const getLayout = Component.getLayout || ((page) => <Layout>{page}</Layout>) return getLayout(<Component {...pageProps} />) } export default ...