Parsing JSON with Fetch in JavaScript is transforming the object

Encountered an odd behavior while using fetch.

Take a look at this screenshot for the correct lengths and structures: console screenshot

Let's examine the JSON response from a server, where the likes array has one object, and the comments array has two:

{
    "status":"success",
    "payload":{
        "272699880986":{
            "likes":[
                {
                    "createdTime":"2016-11-07T04:41:21.000Z",
                    "senderId":10209615042475034,
                    "senderName":"Alfredo Re",
                    "likes":1
                }
            ],
            "comments":[
                {
                    "createdTime":"2016-11-07T04:41:54.000Z",
                    "senderId":1021426764639564,
                    "senderName":"Alfredo J. Re",
                    "comments":1
                },
                {
                    "createdTime":"2016-11-07T04:41:24.000Z",
                    "senderId":10209615042475034,
                    "senderName":"Alfredo Re",
                    "comments":1
                }
            ]
        }
    }
}

When passing the response through response.json(), it returns the following:

fetch('http://example.com/entries.json', {
    method: 'GET',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        ...authKeys,
    }
})
.then(response => {
    switch(response.status){
        case 200:
            console.log('status 200', response)
            return response.json()
    }
})
.then(json => {
    console.log('parsed response')
    console.log(json)
})

The result of this operation is confusing:

{
    "status":"success",
    "payload":{
        "272699880986":{
            "likes":[
                {
                    "createdTime":"2016-11-07T04:41:54.000Z",
                    "senderId":1021426764639564,
                    "senderName":"Alfredo J. Re",
                    "likes": 1,
                    "comments":1
                },
                {
                    "createdTime":"2016-11-07T04:41:24.000Z",
                    "senderId":10209615042475034,
                    "senderName":"Alfredo Re",
                    "comments":1
                }
            ],
            "comments":[
                {
                    "createdTime":"2016-11-07T04:41:54.000Z",
                    "senderId":1021426764639564,
                    "senderName":"Alfredo J. Re",
                    "comments":1
                },
                {
                    "createdTime":"2016-11-07T04:41:24.000Z",
                    "senderId":10209615042475034,
                    "senderName":"Alfredo Re",
                    "comments":1
                }
            ]
        }
    }
}

The likes and comments collections got mixed up. It's really frustrating. Am I missing something here?

UPDATE

Check out this gif showing chrome's console with arrays containing one and two objects respectively. Clicking on them transforms the former into an array with two objects! This is mind-boggling.

Answer №1

After some investigation, I discovered that the culprit behind the object mutation was actually lodash's _.merge(). It seems that it was altering my objects long after they were retrieved. My intention was to merge two collections (likes and comments) based on the senderId key.

As a solution, I opted for a different approach which can be found here:

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

JavaScript button with an event listener to enable sorting functionality

I am looking to implement a button that will reset all the filters on my page. Any ideas? Currently, I have multiple radio buttons for filtering items based on price, size, and color. My goal is to create a reset button that will remove all filters and r ...

Parsing JSON data in PHP and inserting it into a database using a loop

{"details": [{"Ticket_Date":"2014-02-20 11:32:05","Ticket_No":1950,"Amount":1.3,"In_Out":"IN","Vehicle_ID":27,"From_LocationID":3,"PriceType_ID":0,"Trip_ID":"6d744df4dfc017b1-103879384421","To_LocationID":1,"Inspector_Print ":0,"Driver_ID":16}, {"Ticket_Da ...

Refine results by searching through the text contained in the elements of every div

I recently came across a helpful fiddle that allows text to be hidden based on what is entered into a search box. However, I am struggling to apply this method to a div that contains multiple elements. Is there a way to modify the jQuery in the provided fi ...

What methods can be used to monitor changes made to thumbnails on the YouTube platform?

I have embarked on a project to create a Chrome extension that alters the information displayed on the thumbnails of YouTube's recommended videos. In this case, I am looking to replace the video length with the name of the channel. Imagine you are on ...

Debugging Typescript code with line numbers

When opening the console in a browser, typically the javascript line number of a function call or error message is displayed. However, my current setup involves using TypeScript, which gets compiled to Javascript. I am wondering if there is a way to retr ...

Forwarding to another page following an AJAX post request to a Django view

I've been struggling to get this basic piece of code to work properly, despite trying numerous resources. I can't seem to pinpoint where I'm going wrong. Essentially, I have a javascript function submitData() that is supposed to make an ajax ...

VueJS throws an error indicating that the object cannot be extended

I have encountered an issue while trying to update the promo object by adding a new field called colspan. Unfortunately, I am getting this error: uncaught (in promise) TypeError: Cannot add property colspan, object is not extensible at eval (eval at ...

Error encountered when attempting to convert a JSON object to a String using JSON.stringify(), due to a cyclic object value

I have a JSON object with the following structure: obj { name: "abc" , entriesList : "list of entry obj" , propertiesList : "list of properties obj" }; In this structure, an entry is also another object entry { info : "data obj" , ...

Is there a way for me to interpret and process this JSON data?

AngularJS is receiving JSON data from an ArrayList through a get request. The data includes information such as ID, area, gender, and highest education level. 0: Object id:1 area: "State" gender: "Both" highestEd: 36086 ...

Issue with element.onchange not functioning properly with a group of elements

Exploring my Form and Question classes has been an interesting journey. In my "Form" class, I store an array of questions and utilize a method called render() to display each one. render() { let htmlElement = document.getElementById("formBody" ...

jQuery iScroll: The scrolling feature does not stop when reaching the end of the content

Recently, I've been utilizing iScroll for horizontal scrolling on a list. At first, everything seems to be working fine, but as I scroll towards the end (right to left), the content reaches its conclusion yet the scrolling continues beyond that. I&apo ...

Importing files dynamically in JavaScript

Currently, I have a requirement to dynamically import a markup file, extract a portion of the file, assign it to a variable, and then display the result in my React application: import('../changelog.md').then(...) I have attempted to achieve th ...

Emulate a Click Using Pure JavaScript

I am looking to add a click event to my custom dropdown, which replaces a SELECT element. The purpose of this click event is to trigger the corresponding OPTION item when an LI element is clicked. It seems like Woocommerce uses some JavaScript or PHP func ...

Using the ES6 object spread operator in the JSX syntax of ReactJS

// modules/NavLink.js import React from 'react' import { Link } from 'react-router' export default React.createClass({ render() { //for example this.props={from: "home", to: "about"} return <Link {...this.props} a ...

Challenging Trigonometry Puzzles in Javascript

In my project, I am creating an interactive application where a group of humans and bacteria engage in a game of chase. However, I encountered a problem where instead of moving directly towards their target, all entities would veer to the left. I attempt ...

The Angular NgFor directive can only be used to bind data to Iterables like Arrays

I am encountering an issue when attempting to iterate through and display data using ngFor. The specific error appearing in the console is "Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only su ...

The Laravel controller is failing to correctly display content in JSON format

In my Laravel application, I have the following controller: class ProjectController extends Controller { ... public function index() { $projects = Project::where('is_completed', false) ->orderBy('created_at&ap ...

New sorting option added for main page collection

I have a website that displays Question objects using <div> elements. I want to allow users to choose the order in which these items are displayed, but I'm having trouble implementing this feature. My initial approach was to use a <select> ...

Click to reveal the Drop-Up Menu

Looking for a way to create a dropdown menu that opens upwards without using complex scripts? The click events for closing the menu seem to be causing some bugs. Any advice on achieving this using jQuery or JavaScript? Here is the HTML code: <div clas ...

Guide to generating a pop-up on domain-1 with information sourced from domain-2 using jquery, iframes, or any other available method

To clearly explain my issue, I will break it down into steps. In domain-1, I need to insert an iframe or JavaScript code. When domain-1 loads, I want a popup window to appear in the center of the screen, covering the entire page with a faded background. ...