What is the best way to extract and count specific values from a JSON file using JavaScript?

My JSON data looks like this:

/api/v1/volumes:

[
  {
    "id": "vol1",
    "status": "UP",
    "sto": "sto1",
    "statusTime": 1558525963000,
    "resources": {
      "disk": 20000000
    },
    "used_resources": {
      "disk": 15000000
    },
    "lastUpdated": "2019-05-28T20:15:44.585Z"
  },
  {
    "id": "vol2",
    "status": "UP",
    "sto": "sto1",
    "statusTime": 1558525963000,
    "resources": {
      "disk": 50000000
    },
    "used_resources": {
      "disk": 28000000
    },
    "lastUpdated": "2019-05-28T20:15:44.585Z"
  }
]

I want to process this data and calculate the total space occupied in the used_resources.disk fields across all volumes. Additionally, I need to identify the top 5 largest volumes based on used space.

My attempted solution so far:

let _volumes = {
   lastUpdated: 0,
   results: []
}

export function getCapacityByVolumes() {
  if(_volumes.results.length && Date.now() - _volumes.lastUpdated < 1000 * 60) {
    return Promise.resolve(_volumes)
  }
  return fetch('/api/v1/volumes', {
    credentials: 'same-origin'
  })
    .then(result => result.json())
    .then(result => {
      let volumes = result.map(volume => {
        volume.resources = chain(volume.id)
          .groupBy('sto')
          .values()
          .reduce((memo, volume) => {
            return {
               resources: {
                 disk: (memo.resources.disk || 0) + volume.resources.disk
               },
               used_resources: {
                 disk: (memo.used_resources.disk || 0) + volume.used_resources.disk
               }
            }
       }, { resources: {}, used_resources: {}})
       .value()

     volume.largestDisk = chain(volume.id)
        .values()
        .sortBy(vol => vol.used_resources.disk)
        .reverse()
        .take(5)
        .value()

     return volumes
  })
  .value()

  _volumes = {
       results: volumes,
       lastUpdated: result.lastUpdated
  }
  _lastUpdated = Date.now()
  return _volumes
 })
}

Unfortunately, my code doesn't seem to be working properly :( Could it be an issue with the chaining or mapping logic? Any suggestions on how to fix this?

The output I’m aiming for should include the sum of total disk and total used disk grouped by sto, requiring iteration over all volumes (id).

To consume the above function, I am using the following:

class Capacity extends React.Component {
  constructor(props) {
    super(props)
    this.state = {capacity: {}, lastUpdated: null, volumes: []}
  }

  componentDidMount() {
    getCapacityByVolumes()
    .then(result => {
      this.setState({capacity: result.volumes, lastUpdated: result.lastUpdated})
    })
  }

  render() {
    return (
      <div>
        <div className="breadcrumbs">
          <Link to={ '/capacity' } className="crumb">Capacity Dashboard</Link>
        </div>

        <h1 className="m0">Capacity</h1>
        <div>
        {
          chain(this.state.capacity).mapValues((data, id) => {
            return (
              <div key={id}>
                <h2 className="m0">{id.toUpperCase()}</h2>
                <div className="flex flex-wrap">
                  <div className="col col-4 pr3">
                    <h4>Storage Resources</h4>
                    <div className="mb2">
                      Disk capacity
                      <div className="meta-data right">
                        <span className="value">{data.used_resources.disk}</span> used
                        <span className="separator m1">+</span>
                        <span className="value">{data.resources.disk - data.used_resources.disk}</span> available
                        <span className="separator m1">=</span>
                        <span className="value">{data.resources.disk}</span> total
                      </div>
                      <div className="clearfix"></div>
                      <Range
                        value={data.used_resources.disk}
                        total={data.resources.disk} />
                    </div>
                  </div>

                  <div className="col col-4 pr3">
                    <h4>Top 5 Volumes with highest disk</h4>
                    <table className="volumes-table">
                      <tbody className="h6">
                        <tr>
                          <th>Volume</th>
                          <th>disk</th>
                        </tr>
                        {
                          data.largestDisk.map(volume => {
                            return (
                              <tr key={volume.id}>
                                <td><Link to={ '/volumes/' + volume.id }>{volume.id}</Link></td>
                                <td>{formatMB(volume.resources.disk)}</td>
                              </tr>
                            )
                          })
                        }
                      </tbody>
                    </table>
                  </div>
                  <div className="clearfix"></div>
                <hr />
              </div>
            )
          })
          .values()
          .value()
        }
        </div>
      </div>
    )
  }
}

export default Capacity

As a result, I am encountering this error message:

Uncaught (in promise) TypeError: Cannot read property 'dedicated' of undefined

Answer №1

It appears that in your .map call, you are returning volumes instead of volume. This might be causing an issue since volumes is undefined.

Another problem is the error message you're receiving:

Uncaught (in promise) TypeError: Cannot read property 'dedicated' of undefined

If the previous advice resolves the promise with a defined value, there seems to be no property named dedicated in any of the code provided. Therefore, you might still end up with an unexpected undefined value.

Please refer to the comments below:

export function getCapacityByVolumes() {
    if(_volumes.results.length && Date.now() - _volumes.lastUpdated < 1000 * 60) {
        return Promise.resolve(_volumes)
    }

    return fetch('/api/v1/volumes', {
        credentials: 'same-origin'
    })
    .then(result => result.json())
    .then(result => {
        let volumes = result.map(volume => {
            volume.resources = chain(volume.id)
                .groupBy('sto')
                .values()
                .reduce((memo, volume) => {
                    return {
                        resources: {
                            disk: (memo.resources.disk || 0) + volume.resources.disk
                       },
                       used_resources: {
                         disk: (memo.used_resources.disk || 0) + volume.used_resources.disk
                       }
                    }
                }, { resources: {}, used_resources: {}})
                .value()

            volume.largestDisk = chain(volume.id)
                .values()
                .sortBy(vol => vol.used_resources.disk)
                .reverse()
                .take(5)
                .value()

            return volumes // <-- `volumes` is not defined. perhaps you meant `volume`?
        })
        .value()

        _volumes = {
            results: volumes,
            lastUpdated: result.lastUpdated
        }

        _lastUpdated = Date.now() // not sure where this is defined.

        return _volumes
    })
}

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

Tips for adjusting your design when a condition is met:

Currently implementing Material-UI with React framework class App extends Component { constructor() { super(); this.state = { drawerOpened: true }; }; render () { return( <div> <Drawer open={this.state.drawerOpened}> <di ...

Instead of using onload, activate function upon click instead

Upon page load, I have a function that executes: function loadData(page){ showLoading(); $.ajax({ type: "GET", url: "load_data.php", data: "page="+page, success: function(msg) { ...

Instructions for passing the chosen value to Django

I am struggling to set up a search button using Ajax and Django. I need to send the selected value to the server, but I can't seem to retrieve the value from the select HTML tag. The variable value always ends up empty ({"obj":""}). Any ideas? HTML : ...

React Native's fetch function appears to be non-responsive

I am experiencing an issue where the fetch function does not seem to fire in my React Native component: import { Button } from 'react-native'; export function Test() { function submit() { console.log('submit'); fetch('h ...

Converting JSON data into a table format without specifying key names

My database includes a table with a column of VARCHAR(MAX) type that stores JSON key value pairs. The JSON document schema consists of varying numbers of key value pairs, without any nesting or arrays. I am looking to create a query that will present the ...

The babel-preset-es2016 plugin is in need of the babel-runtime peer dependency, however it seems that it

While I am aware that npm no longer automatically installs peer dependencies, why do I still receive a warning after manually installing them? ➜ npm install babel-runtime -g /usr/local/lib └─┬ <a href="/cdn-cgi/l/email-protect ...

What techniques can I use to customize React Bootstrap's css?

Struggling to find a way to override React Bootstrap css without resorting to inline styles. Currently working on rendering an Alert component. https://i.stack.imgur.com/KiATb.png Tried making some CSS modifications, but they're not taking effect du ...

The importance of maintaining property order during deserialization with JSON.Net

I am currently working on deserializing a string into a JSON object using JsonConvert.DeserializeObject as shown below: var str = "{ Value: \"File\",Text: \"OWENS &amp; MINOR INFANT - 2228548\"}"; resultArray = JsonConvert.Deseria ...

My dynamic route with Hooks and route parameters seems to be malfunctioning - what could be causing this

I have been delving into React in my free time, and as a project, I am developing a project management portal. I currently have a dashboard route set up at "/" and a projects route set up at "/projects". My aim is to create a dynamic ro ...

Having trouble getting react-draft-wysiwyg to function correctly within Next.js

I am looking to integrate the react-draft-wysiwyg library with Next.js based on the instructions provided in this helpful guide. [Check out this Rich Text Editor implemented using React Draft Wysiwyg][1] [1]: https://harionote.net/2022/01/07/%E3%80%90reac ...

`Error encountered while parsing JSON data in Python`

Having trouble parsing this JSON in Python '''[{"accountName":"London\"Paris\"Geneva","accountId":"1664800781","isActive":true,"timeZone":"Asia/Jerusalem","currency":"ILS"}]''' This results in the following error m ...

Tips for designing a sleek and seamless floating button

I attempted to implement a floating button feature that remains in view while smoothly flowing using jQuery. I followed a tutorial I found online to create this for my website. The tutorial can be accessed at this link. However, after following all the ste ...

Can I access properties from the index.html file within the Vue.js mount element?

<!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="widt ...

Discovering the RootState type dynamically within redux toolkit using the makeStore function

I am currently working on obtaining the type of my redux store to define the RootState type. Previously, I was just creating and exporting a store instance following the instructions in the redux toolkit documentation without encountering any issues. Howev ...

Running Python in React using the latest versions of Pyodide results in a malfunction

As someone who is new to React and Pyodide, I am exploring ways to incorporate OpenCV functionality into my code. Currently, I have a working piece of code that allows me to use numpy for calculations. However, Pyodide v0.18.1 does not support OpenCV. Fort ...

I am struggling to grasp the flow of this code execution

Hi there, I just started my journey in JavaScript learning about two weeks ago. I would really appreciate it if someone could walk me through the execution steps of the code provided below. function sort(nums) { function minIndex(left, right) { ...

Can you explain the slow parameter feature in Mocha?

While configuring mochaOpts in Protractor, one of the parameters we define is 'slow'. I'm unsure of the purpose of this parameter. I attempted adjusting its value but did not observe any impact on the test execution time. mochaOpts: { re ...

Failure to Refresh Build File in Node.js Environment

Currently, I am in the process of developing a React application. During development, everything seems to be working fine. However, once I attempt to view the final output file, it does not reflect the updates that I have made. For instance, I created a s ...

Animating a div using a changing scope variable in AngularJS

As a newcomer to Angular, I am looking to add animation to a div element using ng-click within an ng-repeat loop. Here is what I have attempted: app.js var app = angular.module( 'app', [] ); app.controller('appController', function($ ...

The function to verify non-mandatory field is malfunctioning

I am facing an issue with a child input component where I am trying to create a test to check if the input is required or not. However, the test fails at the line where it checks for false. expect(fieldNotRequired).toBeFalsy(); Can anyone point out what ...