What is the process for selecting a particular item and adding it to an array that already exists?

api.get(`get-participant-reports/${this.userData.ind_id}`)
      .then((res) => {
        this.reportData = res.data;
        for (var i = 0; i < this.reportData.length; i++) {
          api.get(`get-not-eligible360/${this.reportData[i].id}`).then((res) => {
            this.reportData.push(res.data)
            console.log(this.reportData)
          });
        }
      });

I am working with two API calls and I need to combine the data into one variable. To achieve this, I am using the .push() method to add the data from the second API call to the same variable.

The result is structured as follows:

0:{
    "id": 30,
    "survey_template_name": "Big 5 Survey",
    "report_template_name": "5 Step Profile Report",
    "suborg_name": "Sandbox",
    "program_name": "MNET Testing",
    "iteration_name": "MNET2022 - Test July 2022",
}
1:{
    "id": 3280,
    "survey_template_name": "Big 5 Survey",
    "report_template_name": "5 Step Profile Report",
    "suborg_name": "Sandbox",
    "program_name": "MNET Testing",
    "iteration_name": "iteration-1a",
}
2:{
    "0": {
        "id": 30,
        "not_eligible": "1",
    }
}
3:{
    "0": {
        "id": 3280,
        "not_eligible": "1",
    }
}

My goal is to extract and add the not_eligible information to the existing variable based on their corresponding id. How can I achieve this?

Answer №1

To proceed, it is assumed that you possess response data in the form of an array of objects for both scenarios and there is a necessity to introduce a key called not_eligible into the initial response data based on the ID of the first response data. Therefore, I have modified the code which should be suitable for your requirements.

api.get(`fetch-participant-details/${this.userInfo.participant_id}`)
  .then((response) => {
    this.userData = response.data;
    for (var i = 0; i < this.userData.length; i++) {
      api.get(`retrieve-ineligible360/${this.userData[i].id}`).then((response) => {
        this.userData.forEach(userItem => {
          const existingData = response.data.find(resItem => resItem.id === userItem.id);
            if (existingData) {
              userItem.not_eligible = existingData.not_eligible
            }
        });
        console.log(this.userData)
      });
    }
  });

Answer №2

Utilize the findIndex method to search for a specific item in an array and update its property:

api.get(`retrieve-participant-info/${this.userData.ind_id}`)
      .then((res) => {
        this.participantData = res.data;
        for (var i = 0; i < this.participantData.length; i++) {
          api.get(`check-eligibility/${this.participantData[i].id}`).then((res) => {
            let index = this.participantData.findIndex(item => item.id == res['0'].id)
            if(index > -1) this.participantData[index].eligible_status = res['0'].eligible_status
          });
        }
      });

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

The occurrence of TypeError in next.js Dropzone stating that (0 , _mantine_core__WEBPACK_IMPORTED_MODULE_0__.rem) is not a function is indicating

I am encountering an issue while trying to render a dropzone component using Next.js and Mantine. For reference, I am following the documentation at . Here is the import statement: import dropzone I am receiving an error message that says: I have inclu ...

Retrieving Data from a Promise - { AsyncStorage } React-Native

Currently, I am grappling with figuring out how to retrieve the outcome of a promise. My journey led me to delve into the React Native documentation on AsyncStorage available here: https://facebook.github.io/react-native/docs/asyncstorage I decided to uti ...

Creating a decorative ribbon in three.js for your gift presentation

How can I create a ribbon for a gift box using three.js, similar to the example shown here: Is it possible to create the ribbon with just one piece or do I need multiple pieces to achieve the desired look? Thank you :) ...

The content in the v-tabs is overflowing, yet the arrow indicators are not functioning as intended

Here is some code I'm working with: <v-toolbar> <v-tabs next-icon="mdi-arrow-right" prev-icon="mdi-arrow-left" show-arrows="always" hide-slider icons-and-text cen ...

Looking for a solution to troubleshoot issues with the updateServing function in JavaScript?

I am attempting to create a function that will calculate the portion sizes for the ingredients on my website. This function is located in the Recipe.js file and appears as follows: updateServings(type) { // Servings const newServings ...

Capturing Click Events from Elements Below: A Step-by-Step Guide

In my layout, I positioned two tables side by side. Each table contains clickable items. By adjusting the margins and using relative positioning, I successfully moved the second table to be below the first one. However, a problem arose where clicking on it ...

"Is there a way to extract a specific value from an XML file based on another element

<dataset> <study recNO="0" seriesRecCount="1"> <patientID>123456</patientID> <accessionNumber>M120170428105320</accessionNumber> <patientIDID>35</patientIDID> <studyUID>2.25.1439 ...

Aligning checkboxes in Vue.js: Centering checkboxes inside table cells

Having trouble with aligning checkboxes in a Vue.js application. I want them centered within their table cells, but they keep aligning to the left. When I apply CSS styling to center them, they all unexpectedly align vertically to the leftmost column of th ...

Creating an asynchronous function in Node.js that returns a promise, but experiencing unexpected behavior when using console.log to display the result

Recently, I created a simple and compact API that determines the gender of a person. It functions by sending a get-request to a specific page which responds with a JSON object. This snippet illustrates how my module works: 'use strict'; const ht ...

Integrate an input field with a copy function similar to the GitHub clone view

Can anyone help me create a view with a tooltip similar to the one on Github? You can see the example here: https://i.sstatic.net/iBSof.png I attempted to use CSS but couldn't quite replicate the exact UI. Here is my current CSS code: [tooltip] { ...

Is there a way to align my two tables next to each other using CSS?

.page { display: grid; grid-template-columns: 1fr 1fr; grid-gap: 20px; } .items { float: left; } .secondItem { vertical-align: text-top; float: right; } .page-header table, th, td { border: 1px solid; display: block; background-color: ...

Is it possible to retrieve several columns using the pluck method in Underscore.js following the input from the where method, similar to LINQ

var persons = [ {name : "Alice", location : "paris", amount : 5}, {name : "Bob", location : "tokyo", amount : 3}, {name : "Eve", location : "london", amount : 10} ]; var filteredResults=_.pluck(_.where(persons, {location : "paris"}), 'nam ...

Make the card change to gray when clicked using Bootstrap

Is it possible to achieve a common function in an infinite list using HTML, CSS, JS, jQuery (on the user's side) where an item will be grayed out after being clicked? How can we implement this effect? 1.) When the user clicks on the card element htt ...

Error encountered while integrating AngularJS date picker

I am facing an issue while trying to set up the AngularJS date picker from this link. I am getting an error message that I don't quite understand. Could it be due to a missing library file or just syntax errors? var myApp = angular.module('myA ...

Unable to locate element in Internet Explorer when using frame switching within Selenium

I am currently working on a project in Selenium that is specifically designed to run in Internet Explorer, but I am encountering issues locating the xpath element. Despite this setback, I managed to make progress in the test by using the switch frame func ...

Discovering whether a link has been clicked on in a Gmail email can be done by following these steps

I am currently creating an email for a marketing campaign. In this email, there will be a button for users to "save the date" of the upcoming event. I would like to implement a feature that can detect if the email was opened in Gmail after the button is cl ...

Showing nested JSON data in ng-repeat

Currently, I'm struggling to understand how to access nested JSON and show it on a page using Angular. For instance, consider the JSON structure below where I want to display connectivity products under portfolio using ng-repeat... { "addons": [ ...

Issues with Unity JSON API

I am currently facing a challenge as I attempt to save an n x m field array as JSON in a text file within Unity. Due to the limitation of Unity not supporting array types for top-level JSON deserialization, I have created a custom class structure like this ...

How can you flip an array in C?

Hey there, I'm having some trouble reversing my array. I've checked my syntax and logic, but it seems like the FOR loop is not iterating through as expected. This function is designed to reverse arrays, specifically strings. #include <stdio.h ...

When the second history.push is triggered in react-router-dom, it may result in returning an

Hello, I am working with an Antd modal that contains a form. The code snippet for the modal is as follows: <Modal visible={visible} onOk={handleOk} onCancel={handleCancel}> <MyForm onSubmit={handleOpenUrl}> <CustomInput name= ...