The response from the XHR object is coming back as "Object Object

Recently, I've been faced with the challenge of working with an API that provides articles. Within the array returned by the API, there are attributes like author, title, and description. However, despite my efforts, each time I attempt to retrieve this data, all I get back is 'Object Object'.

I have experimented with different methods such as innerHTML, console.log, and now attempting p.textContent. While p.textContent does allow me to access and display some data, it's still not retrieving the specific information I require.

   xhr.onreadystatechange = function() {
      // Only execute if the request is complete
    if(xhr.readyState !== 4) return;
    // Process the returning data
    if(xhr.status >= 200 && xhr.status < 300) {
        // Executed when the request is successful
        var data = JSON.parse(xhr.responseText);

      var body = document.querySelector('.loadNews');
      // Create a paragraph element
      var p = document.createElement('p');
      // Update the content of the p element with API data
      p.textContent = JSON.parse(xhr.responseText);

      // Append the p element to the body
      body.appendChild(p);

The issue persists, resulting in 'Object Object' instead of the desired data from the API response.

Answer №1

When using the JSON.parse method with an object string as input, it will return an object. If you attempt to treat this return value as a string and print it, you will see [object Object]. To access the properties of the object correctly, you should do something like:

data = JSON.parse(xhr.responseText);
p.textContent = 'author: ' + data.author;

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

Checking connectivity in an Ionic application

Within my Ionic application, I am faced with the task of executing specific actions depending on whether the user is currently connected to the internet or not. I plan on utilizing the $cordovaNetwork plugin to determine the connectivity status within the ...

Ways to retrieve a specific field from an array of objects stored in a text document

Struggling to extract solely the refresh_token field from a text file using file_get_contents. Any assistance would be greatly appreciated. {"access_token":"XXXX","token_type":"bearer","expires_in":3600,"refresh_token":"XXXX"} ...

How to set and update the value of a TextField in ReactJS using useState and implement an onchange event handler for the input field in TypeScript

Just starting out with ReactJS and MUI development, I have a form with a MuiText field in TypeScript. Seeking assistance on how to use the useState method to update the text field value. Additionally, looking for guidance on adding an onchange function to ...

Splunk spath versus regular search speed: which one comes out on top

Consider a scenario where I have JSON logs structured as follows: { level: INFO, logger: com.mantkowicz.test.TestLogger, message: Just a simple test log message } What sets apart the following two search queries? A) ... | message = "Just ...

Node.js removes leading zeroes from dates

I am looking to generate a string with the current date and time in the format: "2021-06-02 09:37:38" const today = `${new Date().toLocaleDateString('sv-se')} ${new Date().toLocaleTimeString('sv-se')}`; console.log(today); ...

Determine the originating component in React by identifying the caller

Can you explain how to access the calling component in a React application? function MyCallingComponent() { return <MyReadingComponent/> } function MyReadingComponent() { console.log(callingComponent.state) } ...

JQuery Keyup event is not functioning as expected

For my blog navigation, I have set up an event where pressing the 'J' key takes me to the previous post and the 'K' key takes me to the next post. However, I am facing an issue where the event works initially but stops working after the ...

Using a data() object in Vue to fill out form fields efficiently

My data retrieval process from mongodb involves obtaining the data and transferring it to the client side using the following approach: error_reporting(E_ALL); ini_set('display_errors', '1'); require '../vendor/autoload.php'; ...

Can TypeScript automatically deduce keys from a changing object structure?

My goal here is to implement intellisense/autocomplete for an object created from an array, similar to an Action Creator for Redux. The array consists of strings (string[]) that can be transformed into an object with a specific shape { [string]: string }. ...

Obtain the final value within a URL's path segment

If we have an href similar to: http://localhost:8888/#!/path/somevalue/needthis Is there a way to extract the last value in the path string (i.e., "needthis")? I experimented with window.location.pathname, but it only returns "/". Another attempt was m ...

Clicking on text triggers image display

My journey in coding is just starting and I have a good understanding of the basics of HTML, CSS, Javascript, and jQuery. I am trying to make an image appear when I click on text but struggling with the implementation. I'm working on a restaurant web ...

Enhancing user experience with AngularJS: Harnessing ng-Click for seamless task management on display pages

I'm struggling with my TodoList in AngularJS. I need help creating the ngClick function for the "addTodo" button. My goal is to send the entire form data to another page where I can display the tasks. Can someone guide me on what needs to be added to ...

How can I transform this imperative reducer into a more declarative format using Ramda?

I am currently working with a reducer function that aggregates values in a specific way. The first argument is the aggregated value, while the second argument represents the next value. This function reduces over the same reaction argument, aggregating th ...

Tips for adjusting the color of multi-line text when hovering with the mouse

I'm facing a challenge in changing the color of text when someone hovers over it, but so far I've only been able to make it work if the mouse scrolls over the top border of the text. The text I'm testing is located in the top left corner an ...

React - The prop value remains static even after the parent component updates its related state

My Application consists of two main components: Button and Input Upon clicking the Click to update state button, the input value initially set as May should be updated to May New. However, I noticed that this change is not taking place. Upon inspecting t ...

Remove identical options from the dropdown menu

After hard-coding and adding items to the dropdown list for team size, such as 1, 2, 3, I am encountering an issue when loading it for editing or updating. Duplicate values are appearing in the list: 1 1 2 3 4... How can I remove these duplicate value ...

How can I index a specific JSON file using elasticsearch-py?

After reviewing this resource on how to index JSON files in elasticsearch using Python, I am still encountering an issue where my JSON file is being recognized as a single document only with ElasticSearch creating fields like '0.created_at' as ob ...

preserve functionality when switching between pages

I have created two simple functions that can change the background color of the body. <script type="text/javascript"> function switchBackground(color){ document.body.bgColor=color; } </script> I am using links with onclick to execute thes ...

Access the value of a JavaScript variable declared in one function within a separate function

Despite finding numerous posts on this topic, none of them suited my specific requirements. My goal is to utilize the seconddivval variable in the datepicker to display available dates. In my PHP code, I have a foreach loop with a hidden input: <td cl ...

Using Gradle: Leveraging the output file data of one task for another task

Challenging Situation I need to update HTML files before packaging them in a WAR file to include a HASH variable that corresponds to a JS bundle compilation. This is the current situation: <script th:src="@{/static/js/assistance/manifest.js}" charset ...