What steps would you take to retrieve this data from the API?

I am a newcomer to working with express and currently dealing with thedogapi for backend development. I am facing difficulties in retrieving specific information (temperaments) from the API. The example data from the API is as follows:

    },
"id": 1,
"name": "Affenpinscher",
"bred_for": "Small rodent hunting, lapdog",
"breed_group": "Toy",
"life_span": "10 - 12 years",
"temperament": "Stubborn, Curious, Playful, Adventurous, Active, Fun-loving",
"origin": "Germany, France",
"reference_image_id": "BJa4kxc4X",
"image": {
"id": "BJa4kxc4X",
"width": 1600,
"height": 1199,
"url": "https://cdn2.thedogapi.com/images/BJa4kxc4X.jpg"
}

I need help extracting only the temperaments from this data so that I can save them in my database. Despite trying different approaches, I haven't been successful so far. Here's an attempt I made:

const getTemp = await Temperament.findAll()
if (getTemp.length === 0){
  const apiAxios = await axios.get(`https://api.thedogapi.com/v1/breeds?api_key=${API_KEY}`)
  
  const infoToGet = await apiAxios.data?.map(el => {
    console.log(el.temperament?.split(",").map(el => el.trim()).toString())
    return {
      temperament: [el.temperament]?.join().split(",").map(el => el.trim()).toString()
    }
  })
  const dbSave = await 

Temperament.bulkCreate(infoToGet)
}

The above code did not yield the desired results, even though it partially worked for extracting temperaments. I sought advice, but the suggested solution involving array methods also did not work. Here's the code snippet using array methods:

router.get("/temperaments", async (req, res) => {
    const temperamentsApi = await axios.get(`https://api.thedogapi.com/v1/breeds?api_key=${API_KEY}`)
    const temperaments = temperamentsApi.data.map( el => el.temperament)
    const tempEach = temperaments.map(el => {
        for (let i = 0; i < el.length; i++) return el[i]})
        console.log(tempEach)
    tempEach.forEach(el => {
        Temperament.findOrCreate({
            where: { temperament: el }
        })
    })

    const allTemperaments = await Temperament.findAll()
    res.send(allTemperaments)
})

I'm seeking guidance on how to make the last code snippet work specifically for the TEMPERAMENT part. Apologies for the lengthy explanation, I am new to this and truly stuck at this point :s

Answer №1

As per the API documentation:

Here's an example along with some code snippets that could be helpful for you. In your code, the variable "temperamentsApi" contains the API response. To extract specific data, you can use the following code:

let result=[];
temperamentsApi.data.forEach(datum=>{
    result.push(datum.temperament);
});
console.log(result);

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

Decrease initial loading time for Ionic 3

I have encountered an issue with my Ionic 3 Android application where the startup time is longer than desired, around 4-5 seconds. While this may not be excessive, some users have raised concerns about it. I am confident that there are ways to improve the ...

Adding a statement in pug/jade is essential for enhancing the functionality

Is there a way to use a variable from my CMS to reference an include template in a specific format? extends layout include layouts/#{data[0].fields.layout}.pug The code is currently looking for layouts/#{data[0].fields.layout}.pug instead of the desi ...

Generating a JSON data structure using Google Spreadsheets

My current project involves learning AppScript through the use of Google Sheets as a practical example. I am attempting to generate a simple JSON object using data stored in the Sheet. Table Example [ { "Name": "ABC", "ID": "123", "Price": ...

Failed to retrieve the requested item using fetch, encountering a NetworkError

My API is being accessed to retrieve data using this code snippet. It sends the email and password to the API: onSubmitSignIn = () => { fetch('http://localhost:3001/signin', { method: 'post', headers: {'Content-Type&ap ...

Checking authentication globally using Vue.js

In the main blade file, I have the following code snippet: <script> window.App = {!! json_encode([ 'csrfToken' => csrf_token(), 'user' => Auth::user(), 'signedIn' => Auth::check() ...

Manually detecting changes in the query string using AngularJS

My AngularJS application includes an edit form with a routing URL like app/edit/:id. When I navigate to app/edit/5, I am able to edit the object with ID 5. However, if I manually change the URL to app/edit/6, the application loads the object with ID 6 in ...

A guide on converting JSON without using the "&quot" symbol

let newText = [{&quot;name&quot;:&quot;en3&quot;,&quot;value&quot;:234},{&quot;name&quot;:&quot;en4&quot;,&quot;value&quot;:135},{&quot;name&quot;:&quot;en1&quot;,&quot;value&quot;:335 ...

Guide to highlighting manually selected months in the monthpicker by utilizing the DoCheck function in Angular

I'm facing an issue and I could really use some assistance. The problem seems quite straightforward, but I've hit a roadblock. I have even created a stackblitz to showcase the problem, but let me explain it first. So, I've developed my own t ...

Using array index to group colors in Javascript

Below is an array that I have: const colors = ['#54AAED', '#7BEA6B', '#f8b653', '#ff5584'] I am working on creating a function that can return a color based on the parameter group and index. For example: function ...

What is the maximum number of requests that Node-Express can send simultaneously?

Currently, I am facing a challenge with my script that involves fetching 25,000 records from AWS Athena, a PrestoDB Relational SQL Database. For each of these records, I need to make a request to Athena and then another request to my Redis Cluster once the ...

Calculate the total sum of a specific property within an array using ES6

My goal is to calculate the total unit value by date and create a new array without duplicate dates. For instance, I want to sum up the values of 2015-12-04 00:01:00. This particular date appears twice in the dataset with values of 5 and 6, resulting in: ...

The function User.find does not exist and it is not possible to replace the `users` model after it has

Currently, I am experimenting with using mongoose, mongoDB, next, and express in a test project. Despite referencing solutions like Cannot overwrite model once compiled Mongoose and others, I am encountering issues unique to my situation. Upon initializat ...

Could a personalized "exit page" confirmation be created?

I am looking for a solution that will allow me to pause the execution of my code, display a dialog box, and then resume execution only after a specific button is pressed. For example, if a user navigates from one page to another on my website, I want a di ...

Implementing additional states in an AngularJS app configuration with Ui-Router

Currently tackling a major application with numerous routes for its different components, my team and I have decided to break down the routes into separate files instead of cramming everything into one large file. In attempting to create a variable and im ...

Assign characteristics to the button, however it will only activate after being clicked twice

The button I created with some bootstrap attributes is not working properly on the first click. To resolve this, I initially called the function in onload and then again on the button click. However, I am now unable to do so and am seeking alternative solu ...

Displaying handpicked phrases [Javascript]

When you click your mouse on a sentence, the words inside are highlighted. This feature works flawlessly. However, trying to display the selected words using the button doesn't seem to be functioning as intended. JSFiddle words = []; var sentence ...

Tips for switching between two CSS classes for a single control in ASP.Net

<style type="text/css> .CssStyle1 { font: 10pt Verdana; font-weight:700; color: Green; } .CssStyle2 { font: 15pt Times; font-weight:250; color: Blue; } </style> <as ...

Do HTTPS Express (Node.js) applications encrypt socket.io messages?

As I develop an Express (Node.js) application that incorporates socket.io on one end, and an authentication system on the other end, a concern arises regarding passing sensitive information to authenticate socket requests. While encrypted post data and htt ...

Ways to loop through an array of daytime values and exhibit just the records for the current week

ng-repeat="day in task.DailyWorks | limitTo : weekdays.length: weekStart" This iteration process enables me to showcase the daily work records in a structured format within the table columns. The feature allows for seamless navigation between different we ...

Navigating with Angular's router occurs before the guard is fully completed

Within my Angular 8 application, the routing file is structured as below: const myRoutes: Routes = [ {path: '', component: FirstComponent , canActivate: [RegistrationSrcdGuard]}, {path: 'FirstComponent ', component: FirstCompon ...