Converting a nested array of objects into an array of objects using async/await and two loops

Although this question may seem similar to others, my case is unique. I have already implemented a solution using a Synchronous loop, but now I want to switch to an Asynchronous loop. Unfortunately, I am struggling to make this transition.

Synchronous loop Solution :

Data input is retrieved from an API.

let input = [  
   {  
      "id":1,
      "domain":"bank",
      "projects":[  
         {  
            "id":1,
            "name":"home loan",
            "amount":["123","345","45"]
         },
         {  
            "id":2,
            "name":"car load",
            "amount":["123","34","45"]
         }
      ]
   },
   {  
      "id": 2,
      "domain":"game",
      "projects":[  
         {  
            "id":3,
            "name":"cricket",
            "amount":["13","4","45"]
         },
         {  
            "id":4,
            "name":"Kabadi",
            "amount":["3","4","5"]
         }
      ]
   }
];

const transformation = data => {
  let counter = 0;
  let domainProjects = [];
  for (let index = 0; index < data.length; index++) {
    let len = data[index].projects;
    for (let j = 0; j < len.length; j++) {
      domainProjects[counter] = {
        domain: data[index].domain,
        project: len[j].name,
        amount: len[j].amount,
      };
      counter++;
    }
  }
  return domainProjects;
};
const result = transformation(input);
console.log("Result:",result);

Asynchronous loop expected result :

expectResult =[
    {
        "domain":"bank",
        "name":"home loan",
        "amount":["123","345","45"]
    },
    {
        "domain":"bank",
        "name":"car load",
        "amount":["123","34","45"]
    },
    {
        "domain":"game",
        "name":"cricket",
        "amount":["13","4","45"]
    },
    {
        "domain":"game",
        "name":"Kabadi",
        "amount":["3","4","5"]
    }
];

Answer №1

This code snippet is a starting point and not thoroughly tested, so use it with caution. It provides a general framework that can guide you in achieving the desired outcome. To iterate through a loop asynchronously, make sure to include async and await statements.

const processData = async () => {
    let count = 0;
    let processedData = [];
    return new Promise((resolve, reject) => {
        for (let i = 0; i < inputData.length; i++) {
            let projectsLength = inputData[i].projects;
            for (let j = 0; j < projectsLength.length; j++) {
                processedData[count] = {
                    domain: inputData[i].domain,
                    project: projectsLength[j].name,
                    amount: projectsLength[j].amount,
                };
                count++;
            }
        }
        resolve(processedData);
    });
}

const finalResult = processData(inputData).then((output) => console.log(output));

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

Exciting Update: Next.js V13 revalidate not triggering post router.push

Currently using Next.js version 13 for app routing, I've encountered an issue with the revalidate feature not triggering after a router.push call. Within my project, users have the ability to create blog posts on the /blog/create page. Once a post is ...

How to tally items according to their status and store utilizing JavaScript?

I have a JSON array and I am looking to add a new field to each object which will represent the count of that object. The count should be based on the status, shop, and name in the ownerDetails property. How can I achieve this? The expected output is pro ...

Using an array in jade rendering

I'm currently working on a node.js server using express and I'm facing an issue with passing an array to jade rendering. Here's the code snippet from my node.js file: router.get('/render', function(req, res) { var t; var ...

Should I generate a new object or utilize an already existing one?

When working with JavaScript and needing to replace existing data with new data, what is considered a good or "correct" practice? I currently utilize Dojo's Memory and dGrid to showcase my data. The information is refreshed each time the user clicks ...

The framework for sending a post request with Retrofit

When attempting to make a POST-request in Android, I encountered some issues. Previously, I had tested it successfully in Postman. https://i.sstatic.net/1ho2z.png However, when using Retrofit2 in Android, I faced difficulties connecting to the server. H ...

Java cookies are utilized to download a file using JavaScript

When I attempt to download a file using Java code, I receive HTML code instead of the actual file contents. Interestingly, if I directly visit the download URL in a browser, the file automatically downloads: <html> <body> <script type="text ...

What is preventing me from binding the array index to a model in AngularJS with two-way binding?

I'm currently facing a challenge with a seemingly simple task: I have an array of string values that I want to link to a select element's options, and then connect the index of the chosen value to a variable. However, I have found that neither us ...

Is it possible to decode JSON using Decodable?

I am facing an issue with a JSON file: { "name": "Jens", "time": "11.45", "date": "2018:04:17", "differentTimestamps":[""] "aWholeLotOfnames":{ "name1": "Karl" "name2": "pär" } What is the proper way to parse the above JSON data? I have referred ...

What should be used for data fetching in Next.js: SWR or traditional fetch/axios along with useEffect?

I'm currently diving into the world of Next.js and I'm eager to showcase data based on user input queries. However, I'm uncertain if leveraging useSWR is the most suitable approach to tackle this challenge because I haven't come across ...

Remove duplicated 1:M structures from JSON documents

I am faced with a challenge involving 700 JSON files, each containing repetitive vulnerabilities like the following: { "vulnerabilities": [ } { "vulnerabilities": [ } These JSON representations highlight instances of vulnerabilitie ...

Is there a way to substitute the final character in the specific regex I've selected?

I have a specific string that I need to modify from {Rotation:[45f,90f],lvl:10s} to {Rotation:[45,90],lvl:10}. Here is the code I tried: const bar = `{Rotation:[45f,90f],lvl:10s}` const regex = /(\d)\w+/g console.log(bar.replace(regex, '$&a ...

Issue with the functionality of Material-ui tooltip

I'm exploring the implementation of the material-ui tooltip feature and I am hoping to have it displayed at the top of the element. Despite specifying placement="top", the tooltip still does not appear as intended. You can view a demo of this issue b ...

Troubleshooting Issue: Ajax Jqgrid Grid Reload Failure in c# .net Environment

Currently, I am encountering an issue with the Refresh button on my grid not working when using a web method to retrieve a JSON response. Below is the code snippet: [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static string get ...

The React component is being rendered repeatedly

I am new to React and decided to implement some functionalities to enhance my understanding of the framework. Currently, I am working on a search feature that displays results in a table format. Each row in the table has a delete option, which triggers a p ...

Issue with Axios response processing

I need to upload a new document into a database using Axios in React. I have successfully implemented the functionality, but I also want to display a message in the console saying "New post has been inserted". This is my front end code: newTodo(todo){ ax ...

Utilizing Firebase SDK to verify jsonwebtoken

Currently, I am utilizing jsonwebtoken on the server using node to authenticate client requests (specifically with firebase 2.x sdks): const jwt = require('jsonwebtoken') jwt.verify(token, <firebase_secret>, (err, decoded) => { }) Up u ...

Update the chosen option in a dropdown list with jQuery and javascript

I need to set the value of a column in a repeater so that once it's assigned, the column will display the current selection from the dropdown. I have the correct value to assign in $('#myname_' + rowIndex).text(), but when I try to assign t ...

How do I add an onClick event to a <span> element within a react-contenteditable component in React?

Is it possible to implement a similar functionality like this: <span onClick={(e) => console.log(e)}>Testing</span> Within the context of react-contenteditable in order to handle the click on the keyword Testing? Using the html prop, only ...

Password Field Validation in React

<TextField id="outlined-basic" label="Password" variant="outlined" /> Can anyone assist me in implementing password validation using an onchange function? I am seeking help with the ...

How to insert an HTML element in between multiple list items using jQuery

I have a variety of div elements that I want to group together using jQuery's append method: Here are the initial div elements: <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div& ...