Struggling to iterate through the response.data as intended

Assume that the response.data I have is:

{
    "data": {
        "person1": [
            {
                "name": ....
                "age": xx
            }
        ],
        "person2": [
            {
                "name": ....
                "age": xx
            }
        ],
        "person3": [
            {
                "name": ....
                "age": xx
            }
        ]
    }
}

In my attempt to add a gender field to each person using the map function, I wrote this code:

axios
    .get('...')
    .then(response => (this.people = [response.data].map(person => {
        person.gender = "";
        return person;
    })))

However, only one gender field gets added to the entire response.data rather than to each individual person. What could be the issue here?

The desired outcome should look like this:

{
    "data": {
        "person1": [
            {
                "name": ....
                "age": xx
            },
            gender: ""
        ],
        "person2": [
            {
                "name": ....
                "age": xx
            },
            gender: ""
        ],
        "person3": [
            {
                "name": ....
                "age": xx
            },
            gender: ""
        ]
    }
}

Answer №1

Based on your response format, you can extract the initial response.data entries (this will give you an array of arrays with key and values).

Next, you can utilize the reduce method where the first parameter is the accumulator, and the second parameter is the current [key, value] pair being iterated. The variable value represents the array, so by accessing value[0] which is an object, you can construct your new array as [ { ...value[0], gender: '' }]

const response = {
    "data": {
        "person1": [
            {
                "name": 'john',
                "age": 33
            }
        ],
        "person2": [
            {
                "name": 'mary',
                "age": 22
            }
        ],
        "person3": [
            {
                "name": 'diego',
                "age": 14
            }
        ]
    }
}

console.log(
  Object.entries(response.data).reduce((obj, [key, value]) => {
    obj[key] = [ { ...value[0], gender: ''} ]
    return obj
  },{})
)

Answer №2

The issue lies in not properly iterating through the nested objects within response.data. By using [response.data], you are creating an array with only one element, which is the entire object of response.data. Then, you add the gender property to that single object and return an array containing this modified object.

To solve this problem, make sure to iterate over each individual element within response.data. One way to achieve this is by using Object.values() to get an iterator of these values.

this.people = Object.values(response.data).map(person => ({...Object.values(person)[0], gender: ''}))

For a demonstration, see the following code snippet:

let response = {
    "data": {
        "person1": [
            {
                "name": "Person 1",
                "age": 10
            }
        ],
        "person2": [
            {
                "name": "Person 2",
                "age": 25
            }
        ],
        "person3": [
            {
                "name": "Person 3",
                "age": 47
            }
        ]
    }
};

let people = Object.values(response.data).map(person => ({...Object.values(person)[0], gender: ''}));
console.log(people);

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

Personalizing the arrow positioning of the Angular8 date picker (both top and bottom arrow)

I am interested in enhancing the design of the Angular 8 date picker by adding top and bottom arrows instead of the default left and right arrows. Can someone guide me on how to customize it? Check out the Angular 8 date picker here ...

Guide to using Vue.js and Vue Router to create a sub menu for the children of the current route

I am currently working on customizing the navigation for my Vue application. My goal is to create a main menu at the top that displays all the root level routes, and a side menu that appears when navigating through child routes. Here is an example of what ...

Identifying the Nearest Div Id to the Clicked Element

When a link is clicked, I am trying to locate the nearest div element that has an id. In this specific scenario, the target divs would be either #Inputs or #Stages. For example, if Page1 through 4 is clicked, I want to store the id #Inputs in a variable. ...

The React Native application is working fine on the emulator but is encountering some issues when trying

While the app runs smoothly on an emulator through Android Studio, I encounter an error when trying to run it from the CLI. error Failed to install the app. Ensure that you have set up the Android development environment properly: <a href="https://fac ...

Verify the dates in various formats

I need to create a function that compares two different models. One model is from the initial state of a form, retrieved from a backend service as a date object. The other model is after conversion in the front end. function findDateDifferences(obj1, ...

Changing a class and audio and storing it using browser's local storage

The challenge I am facing: I am currently working on a feature for my website that allows users to toggle the volume on/off and have that setting persist across different pages. Specifically, I want the user's volume preference to be saved when they n ...

Hold off on submitting the form until the location has been obtained

I am facing an issue with my application where it tries to retrieve location settings from the browser, which takes some time. I would like this process to run when the page loads so that the data is available when needed. However, if a user clicks the s ...

Encountering a Sass Dart error "Bad state: Can't access parent outside of a module" while running npm start in a Create React App

My team has come across an unusual error while attempting to npm start a Create React App we are working on. The error message states: Bad state: Can't access __parent outside of a module, resulting in a failed Build process. This issue is new to us, ...

Personalized VueJS Counter

Just started learning VueJS and I've encountered a challenge while attempting to build a custom counter. Here is the code snippet: <template v-for="(ben, i) in plan.beneficios"> <div class="w-80 w-90-480 m-auto pa-hor-5-480" :class= ...

What is the best way to retrieve IMDB movie data using AJAX?

I have created a code to access movie information from IMDB. To download free movies, you can visit my website . To obtain series of movie information, I need to utilize the IMDB API. However, the current code I am using refreshes the page and posts the a ...

Exploring the data within Vue components

I'm struggling to retrieve data in my Vue component. I pass data from view to component using props like this, while working with Laravel: <fav-btn v-bind:store="{{ $store }}"></fav-btn> Here is how my component is structured: <templ ...

Tips for dynamically populating an HTML table with data from a JSON array using JQuery

I have generated an HTML table <table id="top_five_table"> <tr> <td> </th> <th>URL</th> <th width="90">Total Hits</th> <th width="380">Percentage of all Hits</th> </tr> <tr> ...

What kind of data type should the value property of Material UI TimePicker accept?

While reviewing the documentation, I noticed that it mentions any, but there is no clear indication of what specific data types are supported. The value sent to the onChange function appears to be an object rather than a Date object, and in the TypeScrip ...

What is the solution for displaying just a single panel?

Is there a way to ensure that only the hidden text is displayed when clicking on the button within each panel? Currently, both panels are being revealed simultaneously... import React, { useState } from "react"; import "./styles.css"; export default func ...

Unable to display Klout topics using Ajax Json

After successfully displaying the Klout scores, I have encountered an issue with the Klout topics showing up as undefined. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> var settings ...

When attempting to install an npm package from a local directory, I encountered a 404 Not Found error, despite the package existing in the node_modules directory

After installing an npm package from a local directory, I noticed that the package was successfully installed and is located in the node_modules directory. However, upon trying to access the package, I encountered the following error: 404 not found I a ...

Updating items within an array in a MongoDB collection

I am facing a challenge where I have to pass an array of objects along with their IDs from the client-side code using JSON to an API endpoint handled by ExpressJS. My next task is to update existing database records with all the fields from these objects. ...

CSS table property remains unchanged following an ajax request

At first, my table is set to display none, making it invisible in the application. I am using an ajax call so that when a user selects an option, a table is generated and the display property changes from none to block, making it visible. However, the tabl ...

Saving the current date in MongoDB using the save method

Is there a way to have MongoDB automatically populate a field with the current UTC DateTime when saving a document? I'm aware of the $currentDate operator, but it seems to only be accessible within the update method. ...

What could be causing my MongoDB Node.js driver's $lookup aggregation query to not produce the expected results?

In my database, I have two collections: users and roles Each user has an array of roles assigned to them: { _id : 61582a79fd033339c73ee290 roles:[615825966bc7d715021ce8fc, 615825966bc7d715021ce8fd] } The roles are defined as follows: [ { ...