What is the best way to transform a JSON object from a remote source into an Array using JavaScript?

Attempting to transform the JSON object retrieved from my Icecast server into an array for easy access to current listener statistics to display in HTML.

Below is the JavaScript code being used:

const endpoint = 'http://stream.8k.nz:8000/status-json.xsl';    
const serverStats = [];

fetch(endpoint)
    .then(blob => blob.json())
    .then(data => serverStats.push(data));

The above code snippet inserts the object as a singular item in the array. Utilizing the spread method in ES6 does not remedy this issue, as it solely functions on arrays.

Answer №1

There is no need for an array in this scenario. As you are only dealing with a single object, the properties you require can be easily accessed from that object.

const endpoint = 'http://stream.8k.nz:8000/status-json.xsl';    
const serverStats = [];

fetch(endpoint)
    .then(blob => blob.json())
    .then(data =>{
        let source = data.icestats.source;
       // console.log(source)
        console.log('Listeners =', source.listeners, ' Peak=', source.listener_peak)


       console.log('\n ******************* \n')
       // to iterate over all the source key/values
       Object.keys(source).forEach(k=> console.log(k,'=', source[k]))
    
    })
.as-console-wrapper {max-height: 100%!important;}

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

TinyMCE toolbar missing the "hr" option

I am encountering an issue while using TinyMCE as my editor. I have added the plugin as instructed, but I cannot find the "hr" button/option in the editor interface. If anyone has any insights or solutions to this problem, please share! This is how I am ...

The choices in the second dropdown menu will change based on the selection made in the first dropdown menu

Currently utilizing reactJS, I have the choices for two dropdown lists named categories and items. constructor(props) { super(props) } this.state = { categories: [ { "id": 1, "category_name": ...

Calculate the outer product of arrays with varying dimensions

Consider two arrays X,Y for which the outer product is needed to be calculated on their last dimension. For example, result[:,i,j]=X[:,i]*Y[:,j] when both X,Y are 2-dimensional. If I encounter situations where the dimensions of X,Y are unknown and could v ...

Having trouble retrieving the attribute of an appended element in jQuery?

I am facing an issue where I am unable to retrieve the ID-attribute of an element that has been appended into my HTML. Each time I try, the result is always 'undefined'. How can I resolve this problem? jQuery('form#formular').append(&a ...

The endless $digest loop issue arises when attempting to filter an array of objects

Encountered a persistent $digest loop issue while passing parameters to a custom filter defined on the $scope. Here's the snippet in HTML: <ul id="albumListUL" class="fa-ul"> <li ng-repeat="album in GoogleList | myFilter:Field:Reverse t ...

RegEx - Finding exact matches without any additional characters trailing

I am currently trying to find matches in the given strings: 'Los Angeles, CA' 'New York, NY' 'Williamsburg, Brooklyn, NY' by comparing them with the following input strings: 'Los Angeles, CA 90001, USA' 'New ...

Leveraging Circe for JSON string decoding

My Json string contains information about cars and trucks with requesters and providers. val configInfo = { "car": { "requesters": { "request1": "key1", "request2": "key2" }, "provider": { "req ...

Using AJAX to submit a form and retrieve response data in Javascript

After successfully getting everything to post correctly, I encountered a problem with this script. It keeps loading the content into a new page. Could it be related to the way my php file returns it using "echo(json_encode($return_receipt));"? <s ...

Error: The hook call is invalid and can only be made within the body of a function component in ReactJS

Hello everyone, I am currently facing an issue with saving the lat and lng variables in the state within a hook. When trying to do so, I encounter the following error message: "Error: Invalid hook call. Hooks can only be called inside the body of a functio ...

Generate a fresh object if the values within the TypeScript object are identical

How can I filter an object to return a new object containing elements with the same values? For example: allValues = {"id1": 3, "id2": 4, "id3": 3} The desired output is: filteredValues = {"id1": 3, "id3": 3} This is because the keys "id1" and "id3" hav ...

Tips for displaying the HTML content within the autocomplete box

My situation involves a text input and an HTML form where users can submit their name to retrieve information. I am using AJAX to display the usernames dynamically. <div class="hidesearch" id="search" style="width:"400px;"> <inp ...

Exploring multidimensional arrays in PHP

Looking to extract information from a complex array structure $myArray = array( array('id' => 6), array( 'id' => 3, 'children' => array( 'id' => 5, 'c ...

After the ajax call has finished loading the page, I would like to toggle a particular div

When I trigger a click event on an element, it calls a function with Ajax calls. How can I toggle a div (which will be loaded after the Ajax call) once the page is loaded? function triggerFunction(){ $("#trigger_div").trigger("click"); $("#to ...

Guide to utilizing a JWT token within an httpOnly cookie for accessing a secured API endpoint

Utilizing next.js and next-auth for user login authentication with an API. Once the login is successful, a httpOnly cookie named __Secure-next-auth.session-token is stored in the browser. The following is a sample value (not actual data): eyJhbGciOiJIUzUxM ...

Implementing a FadeOut effect for the clicked link

When clicking on each link, I want the same link to fadeOut() after clicking on the ok button in the myalert() function. If clicked on cancel, it should not fadeOut(). How can I achieve this using the myalert() function? For example: http://jsfiddle.net/M ...

Error in Adding Items to React To-Do List

As I work on creating a React todo app following a tutorial, I have encountered an issue. Despite having components and context files set up, the addItem function does not render the item and date into the todo list when the 'Add todo' button is ...

Angular and Spring are producing a 415 Unsupported Media Type error

I have encountered a dilemma where I tried multiple solutions to no avail. The angular service code is as follows: app.factory('service',['$http','$q', function($http,$q){ return { get: function(m){ return $http.p ...

The build process encountered an error due to the absence of ESLint configuration after the import

Having recently worked on a Vue project created using Vue CLI, I found that eslint was also included in the project. Although I haven't utilized eslint much up to this point, I understand that it is beneficial for catching stylistic errors, semantic e ...

Tips for guaranteeing blocking within a loop in Node.JS

While I usually enjoy the asynchronous nature of Node.JS and its callback-soup, I recently encountered an issue with SQLite that required a certain part of my code to be run in a blocking manner. Despite knowing that addressing the SQLite problem would mak ...

Tailored NodeJS compilation incorporating JavaScript modules

Can NodeJS be built together with specific JavaScript modules? I am aware that for native modules, node-gyp can assist with this, but I am unsure about how to accomplish this with JavaScript modules. My goal is to use a custom application without needing t ...