Exploring the intricacies of nested objects

I am currently developing an API that retrieves data from an external source. After processing the business logic, I end up with the following response:

 {
  data: [
    {
      BTC: {
        USD: 46389.84,
        RUB: 3406131.15,
        EUR: 39472.76,
      },
    },
    {
      ETH: {
        USD: 3215.65,
        RUB: 235786.69,
        EUR: 2741.52,
      },
    },
  ],

}

My goal is to eliminate this nesting and simplify the result to:

 {
  data: {
    BTC: {
      USD: 46389.84,
      RUB: 3406131.15,
      EUR: 39472.76,
    },

    ETH: {
      USD: 3215.65,
      RUB: 235786.69,
      EUR: 2741.52,
    },
  },
}

Answer №1

To successfully flatten the objects within the data array without nested keys with objects as values, you can utilize the following code:

const flatData = obj.data.reduce((acc, cur) => ({...cur, ...acc}), {});
const newObj = { data: flatData };

This process involves two key components:

  • The usage of {...cur, ...acc}: This syntax employs the spread operator (...) to unpack and merge arrays or objects together seamlessly.

  • Utilizing the

    x.reduce((acc, cur) => /* new acc */, initialValue)
    method: The reduce function allows us to transform an array into a different structure by iterating over its elements and building up an accumulating object (acc). It is important to return the updated acc in each iteration.

Answer №2

const result = {
    info: [
      {
        BTC: {
          USD: 46389.84,
          RUB: 3406131.15,
          EUR: 39472.76,
        },
      },
      {
        ETH: {
          USD: 3215.65,
          RUB: 235786.69,
          EUR: 2741.52,
        },
      },
    ],
  };

const newData = {
    data: {},
  };

result.info.map((item) => {
  const keys = Object.keys(item).map((key) => key);
  const values = Object.values(item).map((value) => value);
  newData.data[keys[0]] = values[0];
});

To simplify the process, consider using the reduce method or manually handling it like shown above.

Answer №3

The deepmerge() function here provides a more comprehensive approach compared to the shallow copy obtained from using Object.assign() or the spread operator

var deepMerge = function () {

    // Setting up the merged object
    var newObj = {};

    // Merging the object into the newObj object
    var merge = function (obj) {
        for (var prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                // If property is an object, merge properties
                if (Object.prototype.toString.call(obj[prop]) === '[object Object]') {
                    newObj[prop] = deepMerge(newObj[prop], obj[prop]);
                } else {
                    newObj[prop] = obj[prop];
                }
            }
        }
    };

    // Iterating over each object and performing a merge
    for (var i = 0; i < arguments.length; i++) {
        merge(arguments[i]);
    }

    return newObj;

};


const response = {
    data: [
      {
        BTC: {
          USD: 46389.84,
          RUB: 3406131.15,
          EUR: 39472.76,
          SOME_OBJ: {
            USD: 46389.84,
            RUB: 3406131.15,
            EUR: 39472.76,
          }
        },
      },
      {
        ETH: {
          USD: 3215.65,
          RUB: 235786.69,
          EUR: 2741.52,
        },
      },
    ],
}

let deepData = {};

response.data.forEach(obj => { deepData = deepMerge(obj, deepData); })

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

Retrieve a Google map using Ajax in a PHP script

I'm attempting to display a google map on my homepage using the following function: function addressCode(id, concatenatedToShowInMap) { var geocoder; var map; geocoder = new google.maps.Geocoder(); ...

The getInitialProps method does not have access to the Passport user object in the request when the server is running on a different port

I currently have my express server running on a separate port from my client-side nextjs project. Typically, when the server is on the same port as the client, you can use getRequestHandler with next to pass the user object that can be accessed in the cli ...

ESLint warning: Potentially risky assignment of an undetermined data type and hazardous invocation of an undetermined data type value

Review this test code: import { isHtmlLinkDescriptor } from '@remix-run/react/links' import invariant from 'tiny-invariant' import { links } from '~/root' it('should return a rel=stylesheet', () => { const resp ...

Jquery class fails to detect elements on $.get loaded page

//ajaxContent.js////////////////////////////////////////////// <script> $(document).ready(function(e) { $('a').click(function(){ $.get('/next.php', function(data){ $('#container&apo ...

Saving text as an array with: Mongoose, MongoDB, and SimpleDB-mongoose

Within my schema, I define the following: Links: [] When working with a post request in Node.js, my code looks like this: app.post('/add', function (req, res) { var newItem = new db.Item({ Links[0]: req.body.Link1 Links[1]: req.bo ...

What could be causing my PUT and DELETE requests to return a 404 status code?

I have encountered a problem with my MEN back-end app. In the express client router, I declared PUT and DELETE requests but they are returning a status 404 not found error. However, the POST request is functioning correctly. Could this ...

Swapping out ChildNode data for HTML elements

When attempting to replace a node value with HTML content, I encountered an issue where the HTML tags were being displayed on the HTML page instead of applying the intended style. <style> .YellowSelection { background: yellow; } < ...

How to Retrieve Variables from a Separate .json File in Python

Seeking Assistance I am looking for a way to access variables from an external .json file located in the same directory using Python 2.7. (Import statement is not working for me) The goal is to store the variables in the .json file as shown below: valu ...

showing the angular response data in a HTML table layout within a specific div element

I'm currently using the angular-fullstack generator and I've received data in response to a GET request in the form of integer values (1, 2 5, 6 134, 245 236, 567 415, 234 and so on). I'd like to display these values in an HTML t ...

What is the best way to implement automatic scrolling to the bottom of a materialUI drawer in React after a page refresh?

I am facing an issue with my Material UI Drawer, which contains numerous checkboxes and radio buttons for an advanced search page. Whenever a checkbox or radio button is clicked, it triggers an API request to fetch results instantly without requiring a sub ...

Load gallery thumbnails dynamically using JavaScript or jQuery

Currently, I have implemented TN3 gallery in a WordPress website (not as a plugin, but as a jQuery library). While the large images in the gallery load dynamically and do not affect the page load, the thumbnails are all loaded at once, even if they are no ...

Creating a Paytm payment link using API in a React Native app without the need for a server

Suppose a user enters all their details and the total cost of their order amounts to 15000 rupees. In that case, the app should generate a Paytm payment link for this amount and automatically open it in a web view for easy payment processing. Any suggesti ...

Developing interactive checkboxes for individual rows through React.js

Within a form, I have rows containing two inputs each. Upon clicking "add", a new row is created. For the second row onwards, by clicking "add" a checkbox labeled 1 should be added to indicate dependency on the previous row. In addition, for the third row, ...

What is wrong with my notecards that they won't flip properly?

I am currently developing a text-to-flashcard program using HTML, CSS, and JS. One feature I'm working on is the ability to flip all flashcards at once with a single button click. Currently, the program only allows flipping from the back face to the f ...

What is preventing me from accessing the $sceProvider?

Struggling to implement a filter using $sceProvider to decode HTML tags. Here's my current code structure: myApp.filter('decodeHtml', function($sce) { return function(item) { return $sce.trustAsHtml(item); }; However, upon integrating ...

Expressing SOAP with NodeJS

I am working on handling soap requests in Node.js using Express and BodyParser. However, I have encountered an issue where the request is not being properly formatted when consumed - specifically, the first equals (=) sign is getting converted to a colon ( ...

HTML/JavaScript: Embrace the Power of Dynamic Page

I have a unique element in my HTML code: <image src="http://..." style='...'> Using Python-Flask, I pass on a dynamic source address and save it as window.dynamicEmbedding. Now, during page load, I want to change the image's ...

How can one generate an HTML element using a DOM "element"?

When extracting an element from an HTML page, one can utilize a DOM method like .getElementById(). This method provides a JavaScript object containing a comprehensive list of the element's properties. An example of this can be seen on a MDN documentat ...

What happens when the `.push` command runs the "Undefined" function in jQuery - is it possible to execute a number instead?

My script is quite simple - I'm trying to use the push method to add the result of a function called dNumber into the variable named pattern. However, every time I try this, the result is always "undefined". Oddly enough, when I try pushing just plain ...

Updating Angular model remotely without relying solely on the controller

I am struggling to call the addRectangleMethod method from my Javascript code in order to retrieve server-side information into the Angular datamodel. However, I keep encountering an error stating that the method I'm trying to call is undefined. It&ap ...