struggle with converting JSON string into an array from server

After receiving JSON data from the server, I attempted to convert it into an array using:

JSON.parse(response.data.blocks)
    

However, I encountered this error:

SyntaxError: Unexpected token o in JSON at position 1
        at JSON.parse (<anonymous>)
        at contentblocks.js?KHWUmpg:87149
        at <anonymous>
    

I then tried to sort the blocks with:

let blocks = response.data.blocks.sort(function(a,b){
        var x = a.order < b.order ? -1 : 1 
        return x
    })
    

But got an error stating that "sort" does not exist. It seems I need to first convert the "blocks" object into an array so sorting can be done.

This is a snippet of the JSON sent by the server:

{
        "status": "success",
        "blocks": {
            "0": {
                "id": 50,
                "content_id": 25,
                ...
            },
            "1": {
                "id": 51,
                "content_id": 25,
                ...
            }
        }
    }
    

Answer №1

Organizing object properties

Instead of rearranging the object itself, consider extracting its properties into an array and sorting them based on property names.

Suppose your original object (mentioned at the end of your query) is named server_return_object.

To extract the blocks into an object, use

blocks = server_return_object.blocks;

Next, retrieve the keys ("0", "1", etc.) of the blocks using Object.keys().

block_keys = Object.keys(blocks);

You can then create an array with individual elements for each block. The simplest method is to use the .map() function, which operates on a list of items through a specified function.

block_array = block_keys.map( key => blocks[key] );

Now, in block_array, you have an array of blocks that can be sorted according to preference. For instance, to sort by the created_at property, utilize

block_array.sort(function(a,b){return a.created_at > b.created_at } )

Adjust the function within the sort() to prioritize any criterion for sorting. If it's a straightforward sort based on one property, like demonstrated above, use a comparison for greater than or less than. More intricate ordering methods are feasible by incorporating multiple criteria.

Answer №2

Maybe it's already been processed!

A couple of hints.

Already in object form

The data being received from the server is already structured as an object. There is a key called "blocks" that might contain the information you're looking for.

Error with unexpected token "o"

If you encounter the error message "unexpected token 'o'" when using JSON.parse, it means you are attempting to parse an object instead of a string.

Give this a try:

x={hello:3}; JSON.parse(x);

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

Utilize the v-for second argument in VueJS 2 to showcase the index and index+1

For a VueJS 2 project, I am tasked with enhancing the display of the first and second elements in an array by making them stand out from the rest. To achieve this, I am utilizing the v-for syntax to iterate over a child component within a parent component. ...

Create a WebGL object remotely on the server

Exploring potential project ideas, I was curious to see if it's feasible to produce a WebGL scene or object on the server side and then have it rendered on the client. The motivation behind this is that generating a scene typically involves utilizing ...

Pygame: Only the final object out of the three is being displayed by sprites

I am currently working on developing a stage builder that will facilitate the process of adding objects, individually checking for collisions, and other necessary functionalities for each object I add to the code. My approach involves grouping objects and ...

Running the Npm start command encounters an error

My terminal is showing the following error message: Q:\clone\node-cloudinary-instagram\node_modules\express\lib\router\route.js:202 throw new Error(msg); Error: Route.get() requires a callback function but go ...

Total Output Calculation

In my latest coding project, I have crafted a unique algorithm to calculate exam scores with the inclusion of interactive buttons! function incorrectResponse() { var calc = 0; var calc2 = 1; var divElement = document.createElement("div"); divEle ...

A step-by-step guide on how to substitute document.write with document.getElementById('ElementID').innerHTML

As someone who is not a programmer, I often find myself attempting to grasp code and make adjustments through trial and error. Currently, I am faced with the challenge of modifying the document.write function in the function pausescroller within a Joomla m ...

At what point is the args variable required by Dojo?

There comes a point when passing the args variable to an anonymous function in Dojo becomes necessary, even though the function itself may not visibly need it. This can lead to confusion as there is no clear indication on the Dojo help page regarding whe ...

Why is Reactjs axios returning a promise instead of the expected value?

I have been attempting to retrieve data from an API using axios, but all I am getting back is a Promise. The Node.js code: router.get('/isAdmin/:userId/:groupeId', async (req, res) => { let userId = req.params.userId let groupeId = ...

Vue.js mobile app may show a loaded DOM that remains invisible until the screen is tapped

I am facing a peculiar issue that has me stumped. On my mobile device, my page initially loads like this homepage However, once I tap the screen, all the components suddenly appear. Is there a way to simulate a click on my mobile? I'm struggling to u ...

Exploring the world of MVC4: Enhancing user experience with client-side

Solution: The answer provided by @www.innovacall.com is correct, I initially misunderstood it but now it works perfectly. Thank you for the help. Initial issue: I have been struggling with finding a solution to my problem. In my project, there is a mod ...

Switching between different CSS files based on the URL using jQuery or another method

Is it feasible to apply specific styles based on the ID or load various CSS files depending on the URL you are visiting? For example: <script> if(location.href == 'http://jpftest2.tumblr.com/about'){ document.write('<style type= ...

Using the Twit package on the client side: a step-by-step guide

I have been utilizing the Twit package for searching tweets. After executing the js file in the console, I am able to see the tweets but when trying to use them on my webpage, an error 'Uncaught ReferenceError: require is not defined' pops up. Th ...

Iframe Interactivity

My goal is to create an interactive iframe that will match the current parent URL (). For example, if I have an iframe pointing to http://www.google.com and click a link within the iframe, it should update the parent URL to , and then load the clicked con ...

Tally each div individually and display the count within each div, instead of showing the total count across

I have come across various solutions that show the total number of certain special divs, such as: $('.someclass').length However, I am facing a different challenge. I want to sequentially count each div with a numerical sequence. For instance, ...

One helpful tip for adjusting the size of a UI chip on the fly

I am attempting to adjust the size of a UI chip dynamically based on the font size of its parent elements using the em unit in CSS. My objective is to achieve something like this: style={{size:'1em'}} The issue I'm encountering: The chip e ...

AngularJS scope refreshed following search form validation in Symfony2

Hey there, fellow developers! We are currently faced with the task of rewriting a software application in Symfony2 using AngularJS. We have chosen to utilize Symfony2 for its robust MVC capabilities and AngularJS for its powerful functions. Our current c ...

Difficulty encountered when trying to update intricate model using Angular UI modal

My current project involves managing a model containing nested arrays that represent different sections of a floor plan. Each section contains an array of booth objects. To optimize user interaction, I've created a view that displays all the booths on ...

Sharing JSON data across different domains to ASP.NET using jQuery

I have encountered a complex issue. Currently, I am involved in a project that requires generating receipt printouts when users check out on our website at a kiosk. Due to driver and formatting challenges, I am utilizing COM automation with Word for handl ...

The useContext hook was utilized in conjunction with useReducer, however, a child component is unexpectedly showing an

First and foremost, I want to express my gratitude for your unwavering support. As a newcomer to the realm of ReactJS, I am currently navigating through the development of a concept example for a product store that includes various filters in the form of ...

What is the secret behind Redactor JS's ability to display properly indented code snippets?

If you take a look at the Redactor JS demo and click on the button to show the HTML source code of the displayed content... ...you will notice that the code is properly indented: Most rich text editors or wysiwyg editors typically display code in a singl ...