arrange information retrieved from an api

Hey there! I'm currently diving into the world of JavaScript, and it's been quite a journey these past 3 days as I've been attempting to get everything up and running. Despite its apparent simplicity, I can't seem to make things click.

My current challenge involves organizing data that I fetch from an API.

I'm making API requests using axios

axios.get('url').then(function (response) {
  console.log(response.data)
})

The JSON response I receive looks like this

[{
  "item_id": "item_1",
  "city": "city_1",
  "quality": 2,
  "sell_price": 1000,
  "sell_price_date": "2020-05-05T01:20:00"
},
// More JSON objects
]

My goal is to structure the data in the following format:

[{
  "item_id": "item_1",
  "qualities": [
    {
      "quality": 2,
      "cities": [
        // City details
      ]
    },
    // More quality levels
  ],
},
// More item entries
]

After organizing the data, my plan is to create HTML elements dynamically based on the structured data (pseudo code)

<ul class="items" >
  ${db.forEach(item => {
      <li class="item">
        <p class="item_title">item.item_id</p>
        <ul class="item_qualities">

          ${item.qualities.forEach(qual => {
            <li class="quality">
              <p class="quality_title">qual.quality</p>
              <ul class="cities">

                ${qual.cities.forEach(city => {
                <li class="city">
                  <p class="city_title">city.city</p>
                  <ul class="prices">
                    <li class="sell_price">
                      <p class="sell_price_title">city.sell_price</p>
                    </li>
                    <li class="sell_price_date">
                      <p class="sell_price_date_title">city.sell_price_date</p>
                    </li>
                  </ul>
                </li>
              })}

              </ul>
            </li>
          })}

        </ul>
      </li>
  })}
</ul >

In conclusion
As a newbie in the realm of programming and JavaScript, I'm eager to learn by working with real-world APIs. Any guidance or tutorials you could recommend regarding JSON and database handling would be greatly appreciated!

Answer №1

Could you clarify the concept of GROUP here? I noticed that the group's primary level is identified by item_id in your provided code snippet, but I'm curious to know what determines the secondary level grouping for qualities.

let database = []
array.forEach(element1 => {
    if (database.every(element2 => element2.item_id != element1.item_id)) {
        database.push({
            item_id: element1.item_id,
            qualities: [{
                quality: element1.quality,
                cities: [{
                    city: element1.city,
                    sell_price: element1.sell_price,
                    sell_price_date: element1.sell_price_date
                }]
            }]
        })
    } else {
        for (let index = 0; index < database.length; index++) {
            if (database[index].item_id === element1.item_id) {
                let currentQualities = database[index].qualities
                let foundMatch = false
                for (let j = 0; j < currentQualities.length; j++) {
                    if (currentQualities[j].quality === element1.quality) {
                        currentQualities[j].cities = currentQualities[j].cities || []
                        currentQualities[j].cities.push({
                            city: element1.city,
                            sell_price: element1.sell_price,
                            sell_price_date: element1.sell_price_date
                        })
                        foundMatch = true
                        break
                    }
                }
                if (!foundMatch) {
                    database[index].qualities.push({
                        quality: element1.quality,
                        cities: [{
                            city: element1.city,
                            sell_price: element1.sell_price,
                            sell_price_date: element1.sell_price_date
                        }]
                    })
                    break
                }
            }
        }
    }
})

Answer №2

When working with JSON data, it's important to analyze the attributes you receive and determine which ones are necessary for your database. By understanding these requirements, you can then design the structure of your database including the appropriate field types.

After setting up your database, you can begin extracting data from the API. This involves iterating through the incoming entries and inserting each one into your database accordingly.

Answer №3

Your discussion is not specifically related to databases but rather focuses on transforming data obtained from an API into a more usable format. In this scenario, a database would be utilized for storing the transformed data once it has been processed.

One approach is to utilize the JavaScript forEach() method to iterate through each element and apply your custom logic to populate the transformed dataset accordingly.

var transformedData = []    
response.data.forEach(item => {
  ...custom logic to add or update items in the transformed set
})

To get started, you should first check whether the item already exists in the transformedData set before making any modifications.

Best of luck with your transformation process!

Answer №4

Existing Status :

function fetchData() {
  console.log("initiating data retrieval !")

  axios.get('url')
    .then(function (response) {
      response.data.forEach(e1 => {

        if (db.every(e2 => e2.item_id != e1.item_id)) {

          console.log("item not found, creating new one")
          db.push(
            {
              item_id: e1.item_id,
              qualities: [{
                quality: e1.quality,
                cities: [{
                  city: e1.city,
                  sell_price_min: e1.sell_price_min,
                  sell_price_min_date: e1.sell_price_min_date
                }]
              }]
            })

        } else {

          console.log("item located, editing it")
          item_index = db.indexOf(e1.item_id)
          console.log(item_index)

          if (db[item_index].qualities.every(e3 => e3.quality != e1.quality)) {

            console.log("quality not found, creating new one")
            db[item_index].qualities.push(
              {
                quality: e1.quality,
                cities: [{
                  city: e1.city,
                  sell_price_min: e1.sell_price_min,
                  sell_price_min_date: e1.sell_price_min_date
                }]
              })

          } else {

            console.log("quality found, modifying it")
            quality_index = db[item_index].qualities.indexOf(e1.quality)
            console.log(quality_index)

            if (db[item_index].qualities[quality_index].cities.every(
              e4 => e4.city != e1.city)) {

              console.log("city not found, creating new one")
              db[item_index].qualities[quality_index].cities.push(
                {
                  city: e1.city,
                  sell_price_min: e1.sell_price_min,
                  sell_price_min_date: e1.sell_price_min_date
                })

            } else {

              console.log("city found, modifying it")
              city_index = db[item_index].qualities[quality_index].cities.indexOf(e1.city)
              console.log(city_index)

              db[item_index].qualities[quality_index].cities[city_index].city = e1.city;
              db[item_index].qualities[quality_index].cities[city_index].sell_price_min = e1.sell_price_min;
              db[item_index].qualities[quality_index].cities[city_index].sell_price_min_date = e1.sell_price_min_date;

            }
          }

        }

      });

      console.log("data retrieval completed")
      console.log(db)
    })
}

The issue encountered

Uncaught (in promise) TypeError: Cannot read property 'qualities' of undefined
    at index.js:33
    at Array.forEach (<anonymous>)
    at index.js:9

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

Exploring Node.js: Managing Memory Consumption for Efficiency

I'm currently setting up multiple Node applications on one server, and I'm particularly worried about memory usage. Is there a specific amount of physical memory needed for a basic Node.js express service to run? Also, is there a method to limit ...

The new pop-up window appears smaller than expected in Internet Explorer

There has been a bug report regarding the course opening in a smaller popup window. The JavaScript code used to open the popup is: course_window=window.open(urlString,"", "toolbar=0,directories=0,location=0,status=0, menubar=0,fullscreen=0,scroll ...

The program suddenly halts during the second loop without displaying any error messages

I've encountered an issue with my Node.js program on Windows that records microphone sound. The problem arises when I try to record multiple .wav files within a loop while taking user options from a menu. Initially, everything works fine and the prog ...

Issue with executing .then() after Promise.all() in Node.js

Utilizing the nodejs Mongo driver, I am aiming to create backups for small collections and insert data into another collection. The strategy I have devised involves: Defining a function that can back up a collection (by making a collection with the suff ...

Retrieving URL from AJAX Request in Express JS

Currently, I am in the process of developing an Express App and encountering a challenge regarding the storage of the user's URL from which their AJAX request originated. In simpler terms, when a website, such as www.example.com, sends an HTTP request ...

Unclear when notifying div content

After creating a PHP page, I encountered an issue while trying to select the inner text of a div and alert it with jQuery. Instead of getting the expected result, it keeps alerting "undefined." What could possibly be causing this? Here is the code snippet ...

Can an unresolved promise lead to memory leaks?

I have a Promise. Initially, I created it to potentially cancel an AJAX request. However, as it turns out, the cancellation was not needed and the AJAX request completed successfully without resolving the Promise. A simplified code snippet: var defer = $ ...

"npm ci is triggered, raising a warning due to an invalid entry in the tar file, ultimately

Our project is utilizing package-lock.json along with the npm ci command to download and install node_modules. However, we consistently encounter the following messages: npm WARN prepare removing existing node_modules/ before installation npm WARN tar inv ...

Coordinating multiple API requests for optimal performance

I have a task where I need to retrieve data from two different API endpoints. Once both sets of data are fetched, I need to compare the information obtained from each source. I am familiar with fetching data from a single API endpoint and using a callback ...

Analyzing the values provided as input (using setState)

Two event handlers manage passwords. The first, inputPassword, writes the input value to state. The second, inputPasswordRE, writes the input value and compares it to the value from inputPassword. Because setState works asynchronously, even if the same v ...

301 redirection will be implemented on the upcoming static export

Working on a Next.js project, I utilized static export for better performance and SEO. Yet, I've come across an issue with URL changes. I'm looking to incorporate a 301 redirect to ensure search engines and users are directed to the correct pages ...

Modifying a table row in real-time with the power of JQuery/JavaScript

I successfully created a table with a for loop in Java Spring and now I'm trying to dynamically show and hide specific parts of it when a button is clicked. Here's a simplified version of what I have: <jsp:attribute name= "scripts"> ...

How can I incorporate a personalized SVG path to serve as a cursor on a webpage?

Is there a way to enhance the functionality of binding the 'mousemove' event to a div and moving it around the page while hiding the real cursor? Specifically, can we change the shape of the circle to an SVG path and drag the SVG path around the ...

Performing asynchronous ajax calls with jQuery

Here is some code I have that involves a list and making an ajax call for each element in the list: util.testMethod = function(list) { var map = new Map(); list.forEach(function(data) { $.ajax({ ...

The bundle.js file is displaying HTML code instead of JavaScript

I have been working on setting up redux server-side rendering using express.js. Most of the setup is done, but I encountered an error while trying to render the page in the browser. The error message Uncaught SyntaxError: Unexpected token < is appearin ...

Ways to determine if the property of a document has been altered?

Currently, I am in the process of writing tests for an Express CRUD application. The specific route I am focused on is the account recovery route. This route accepts POST requests with an email included in the body. Essentially, the application will search ...

Checking connectivity in an Ionic application

Within my Ionic application, I am faced with the task of executing specific actions depending on whether the user is currently connected to the internet or not. I plan on utilizing the $cordovaNetwork plugin to determine the connectivity status within the ...

Scrolling up or down in an HTML webpage using a script

Seeking a code snippet for my website that will allow me to achieve the following functionality: Upon clicking on text_head1, a list of lines should scroll down. Subsequently, when I click on text_head2, the previous list should scroll up while the new l ...

Develop a JavaScript function to generate a multiple selection form

Hey there! I have a question... Can I use JavaScript to create a multiple select form? Here's an example: <select name="item[]"> <option value="0">Option 1</option> <option value="1">Option 2</option> </select> &l ...

Is Snowflake misinterpreting the timestamp information?

I have been importing semi-structured data (JSON) into my database via Snowflake. The timestamp values within the entries are in javascript timestamps format such as: "time": 1621447619899 After the import, Snowflake auto-transforms these timest ...