Simplify a structure within an object

Currently, I'm troubleshooting a GET request that retrieves an id and the amount of holdings a user has stored in the database. This request then calls a function to fetch updated information about the item. My goal is to also incorporate the holdings in the GET request, but I want it to be nested inside the object containing the updated information. Essentially, I aim to flatten these objects so they form an array of two objects rather than an object within an object. Below is the code I'm working with and the output I'm currently getting. I've attempted to modify the Object.assign part without success; I'm struggling to figure out how to accomplish this.

Current:

const getFullCryptoPortfolio = () =>
  CryptoPortfolio.find()
    .then(portfolios =>
      Promise.all(portfolios.map(portfolio => getCoins(portfolio.id).then(item =>
        Object.assign({}, item, {
          holdings: portfolio.holdings
        })))));

[
    {
        "0": {
            "id": "bitcoin",
            "name": "Bitcoin",
            "symbol": "BTC",
            "rank": "1",
            "price_usd": "9289.45",
            "price_btc": "1.0",
            "24h_volume_usd": "6536340000.0",
            "market_cap_usd": "157138942782",
            "available_supply": "16915850.0",
            "total_supply": "16915850.0",
            "max_supply": "21000000.0",
            "percent_change_1h": "0.36",
            "percent_change_24h": "-3.7",
            "percent_change_7d": "-18.82",
            "last_updated": "1520905166"
        },
        "holdings": 1
    },
    {
        "0": {
            "id": "ethereum",
            "name": "Ethereum",
            "symbol": "ETH",
            "rank": "2",
            "price_usd": "704.491",
            "price_btc": "0.0765146",
            "24h_volume_usd": "1773830000.0",
            "market_cap_usd": "69147117523.0",
            "available_supply": "98151882.0",
            "total_supply": "98151882.0",
            "max_supply": null,
            "percent_change_1h": "0.53",
            "percent_change_24h": "-3.12",
            "percent_change_7d": "-17.17",
            "last_updated": "1520905152"
        },
        "holdings": 2
    }
]

Expected Output Example:

 [
    {
            "id": "bitcoin",
            "name": "Bitcoin",
            "symbol": "BTC",
            "rank": "1",
            "price_usd": "9289.45",
            "price_btc": "1.0",
            "24h_volume_usd": "6536340000.0",
            "market_cap_usd": "157138942782",
            "available_supply": "16915850.0",
            "total_supply": "16915850.0",
            "max_supply": "21000000.0",
            "percent_change_1h": "0.36",
            "percent_change_24h": "-3.7",
            "percent_change_7d": "-18.82",
            "last_updated": "1520905166",
            "holdings": 1
    },
    {
            "id": "ethereum",
            "name": "Ethereum",
            "symbol": "ETH",
            "rank": "2",
            "price_usd": "704.491",
            "price_btc": "0.0765146",
            "24h_volume_usd": "1773830000.0",
            "market_cap_usd": "69147117523.0",
            "available_supply": "98151882.0",
            "total_supply": "98151882.0",
            "max_supply": null,
            "percent_change_1h": "0.53",
            "percent_change_24h": "-3.12",
            "percent_change_7d": "-17.17",
            "last_updated": "1520905152",
            "holdings": 2
    }
]

Answer №1

It appears that the problem lies in how the getCoins method is handling an array of objects that you are attempting to merge with holdings. To resolve this, you can adjust your Object.assign method as shown below:

Object.assign({}, ...item, {
  holdings: portfolio.holdings
});

This code snippet will spread the objects contained within the item array. Keep in mind that if multiple items share the same property, the value will be overridden by the later one.

If the getCoins function consistently returns a single item, you can simplify the code by using:

Object.assign({}, item[0], {
  holdings: portfolio.holdings
});

Alternatively, if you prefer to maintain the array structure, you can individually assign holdings to each object:

item.map(obj => Object.assign({}, obj , {
  holdings: portfolio.holdings
}))

Answer №2

  1. Set all the attributes of "0" to the object 'item';
  2. Set the "holdings" attribute to the object 'item';
  3. return item.

    function compress(list) {
      return list.map(function(item){
        let obj = item["0"];
        obj["holdings"] = item["holdings"];
        return obj;
      });
    }
    

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

Storing knockout view model data in a database and fetching it back

I am currently working on a web form that utilizes knockout, and I need to add a new feature that allows users to save the form as a draft in the database. Later on, they should be able to load it again to make modifications or submit it. Is there a built ...

The special function fails to execute within an "if" condition

As a newcomer to JavaScript/jQuery and Stack Overflow, I kindly ask for your patience in case there are any major errors in my approach. I am currently developing an HTML page with Bootstrap 3.3.7, featuring a pagination button group that toggles the visib ...

The Geolocation API popup on Safari for iOS kept appearing repeatedly

I have successfully implemented a code using the HTML5 Geolocation API to retrieve the user's current position within a mobile website. Although the code functions properly, there is an issue with Safari on iOS. Whenever the page is reloaded, a syste ...

The affix feature in Bootstrap's navbar fails to recognize the height of images

My navbar element affixes prematurely when placed below my header element, making it seem as if the image in the header does not exist. The navbar is meant to affix only when it reaches the top, but currently, it is affixing earlier. The code I used sets ...

Inserting a value into a Node/Express session

I am currently immersed in a project that involves Node, Express, and MongoDB. Mongoose is the tool I use to shape my schemas and interact with the database. In addition, I utilize the "express-sessions" module where a session value named "req.session.user ...

Display the output based on checkbox selection using JavaScript

I am working on a feature where I need to capture checkbox inputs using JavaScript and then store them in a PHP database. Each checkbox corresponds to a specific column in the database. If a checkbox is checked, I want to insert its value into the databa ...

To avoid any sudden movements on the page when adding elements to the DOM using jQuery, is there a way to prevent the page from

I have a challenge where I am moving a DIV from a hidden iFrame to the top of a page using jQuery. Here is my current code: $(document).ready(function($) { $('#precontainer').clone().insertBefore(parent.document.querySelectorAll(".maincontainer" ...

What is the best way to refresh my Material-UI checkboxes following updates to certain states in a React JS environment?

One of my latest projects involves an application that visualizes graphs, with all nodes originally colored blue. I included a component in the form of a checkbox that users can interact with to trigger a state change. This change dynamically alters the co ...

Retrieve the data attribute from a select box that was created dynamically

Following an AJAX request, I have successfully generated two select boxes: $("#job_id").change(function() { var id = $(this).val(); $.ajax({ url: '', type: 'POST', dataType: 'json', dat ...

How can I load 3-D models in three.js by specifying file content instead of the file path?

I'm looking to develop an interactive online model viewer that allows users to easily upload and view models without having to manually edit the source code. Unfortunately, most browsers restrict access to file paths, but can still read file contents. ...

The navigation menu dissolves into hiding at the uppermost part of the page upon scrolling upwards on iOS devices

I am currently working on creating a navigation menu that will automatically hide when scrolling down and reappear when scrolling up. This functionality works perfectly fine on desktop and Android browsers, but I have encountered an issue specifically with ...

Learn the technique of coding HTML within inline JavaScript, along with implementing CSS inline styling

I'm looking for a way to incorporate HTML within inline JavaScript, along with CSS inline styles. Can someone provide guidance on how to achieve this? For example, something like the following code snippet: <p><span style="color: #00ff00;"&g ...

I'm curious to know how this code is extracting parameters from the website URL. Can someone walk me through the process step by step?

I needed to extract parameters from a URL and started searching online for solutions. I came across a helpful link that provided the information I was looking for: After visiting the website, I found this code snippet: function getUrlVars() { var var ...

Approximately 20% of spoken words are not accurately conveyed by Speech Synthesis Google Voices, failing to adhere to the intended voice selection

When using speechSynthesis.speak(utterance) in Chrome with the "Google UK English Female" voice, there is an issue where a male voice is randomly spoken instead. Any thoughts on how to resolve this? Latest Update: July 26th, 2022 This appears to be a bug ...

There are two notable problems with Bootstrap 4 Tooltip. The first is that it appears when a button is clicked, and the second is that it shows up for disabled elements

I am currently experiencing an issue with my tooltip while using Bootstrap 4. In my index.html, I have the following script loaded: $('body').tooltip({ selector: '[data-toggle="tooltip"]', delay: { show: 550, hide: 0 } }); The proble ...

Finding MongoDB data using an Express route and displaying it in a Jade template

Is there a way to retrieve data from MongoDB using an express route and display it in a jade template? Below is the code snippet of my express route (express version 2.5.8): app.get('/showData',function(req,res){ db.collection('comme ...

Do we need to use aria-labelledby if we already have label and input associated with "for" and "id"?

Here is the HTML structure for the Text Field component from Adobe Spectrum: The <label> element has a for attribute and the <input> has an id which allows screen readers to read out the label when the input is focused. So, why is aria-label ...

Exploring the world of JSON files using JavaScript

Basically, my bot responds to a command (!accounts) by providing users with information based on their ID. For example, if an ID of 662 sends the command !account, the bot will search for steamID 662 in the json files and display the currency and correspon ...

Continuous loop of images displayed in a slideshow (HTML/JavaScript)

Greetings everyone, I am currently working on creating an endless loop slideshow of images for my website. Despite researching several resources, I am still struggling to get the code right. The issue I am facing is that only the image set in the HTML code ...

What is the best way to ensure that messages stay saved in my app for an extended

I am looking for a way to store messages sent through my small messaging app in a persistent manner. Currently, the messages are transferred from the front-end to a Node, Socket.io, and Express back-end. A friend recommended using Enmaps (), but unfortuna ...