Create a new object by mapping values from an array of two objects in Angular using TypeScript, based on the object

Here is a code snippet for a Question and Answer data structure:

export class Question {
  id: string;
  title: string;
  description: string;
  answers: Answer[];
}

export class Answer {
  id: string;
  text: string;
  questionId: string;
}

We have two objects, 'answers' and 'questions':

answers =  [
    {
      "id": 1,
      "text": "some comment1",
      "questionId": 1
    },
    {
      "id": 2,
      "text": "some comment2",
      "questionId": 3
    },
    {
      "id": 3,
      "text": "some comment3",
      "questionId": 3
    }
  ];

questions = [
    {
      "id": 1,
      "title": "Name1",
      "description": "typicode1"
    },
    {
      "id": 2,
      "title": "Name2",
      "description": "typicode2"
    },
    {
      "id": 3,
      "title": "Name3",
      "description": "typicode3"
    }
  ];

questionsAndAnswers: Question[];

We now need to link each answer to the correct question under the 'answers' property.

The updated 'questionsAndAnswers' should be:

questionsAndAnswers = [{
      id: 1,
      title: Name1,
      description: typicode1;
      answers: [{
          "id": 1,
          "text": "some comment1",
          "questionId": 1
        }]
},
{
      id: 2,
      title: Name2,
      description: typicode2;
      answers: []
},
{
      id: 3,
      title: Name3,
      description: typicode3;
      answers: [{
          "id": 2,
          "text": "some comment2",
          "questionId": 3
        },
{
          "id": 3,
          "text": "some comment3",
          "questionId": 3
        }]
}
];

Answer №1

If you want to manipulate Arrays, consider using the reduce method in combination with filter. Give this a try:

var questions = [ { "id": 1, "title": "Name1", "description": "typicode1" }, { "id": 2, "title": "Name2", "description": "typicode2" }, { "id": 3, "title": "Name3", "description": "typicode3" } ];
var answers =  [ { "id": 1, "text": "some comment1", "questionId": 1 }, { "id": 2, "text": "some comment2", "questionId": 3 }, { "id": 3, "text": "some comment3", "questionId": 3 } ];
  
var questionsAndAnswers = questions.reduce((acc, curr, index) => {
  acc[index] = curr;
  acc[index].answers = answers.filter(answer => answer.questionId === curr.id);
  return acc;
}, []);

console.log(questionsAndAnswers);

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

How come my data is not appearing on the screen despite receiving a result in the console log?

I am facing an issue with displaying data obtained from Supabase. I am passing the data as a prop and using map to iterate over it in order to show the required values. However, despite logging the correct results for `programme.title`, nothing is being re ...

AngularJS - Retrieving an object with a button click

I have an array of objects with names displayed in input fields. I want to update the corresponding object with whatever the user fills in the input field when they click the button. For example, if I enter “abcde” and “pq” in the input fields, th ...

When trying to use bootbox.confirm within a dynamically loaded AJAX div, the modal unexpectedly opens and

I have implemented bootbox into my project, which was downloaded from . user_update.php is being loaded in a div within users.php using ajax functionality. Within user_update.php, there is a JavaScript function called validateForm(). Right after the functi ...

Learn how to incorporate latitude and longitude coding into PHP to display a map icon that correctly redirects to the desired URL when clicked

I am in need of a table that includes buttons for adding, editing, deleting, and mapping. Everything works fine so far, but when I click on the map button, it should take me to Google Maps with coordinates linked from a MySQL database containing latitude ...

JavaScript, XML, and PHP all support the use of HTML entities within their code

Having some trouble as a newbie again))) Can you please help me out, guys? I'm having an XML file with the following data: <Page> <Content>&lt;p&gt;Article content&lt;/p&gt;&#13; &#13; &lt;h1 style="font-style ...

Running and storing JavaScript in NEW Selenium IDE: A comprehensive guide

I am facing a challenge with updating my old test scripts that were originally created for the outdated Selenium IDE. The task at hand is to modify them to work with the latest version of Selenium, but I am struggling to make sense of how to handle section ...

Conceal items by clicking using raycasting technology

I'm trying to hide scene objects by clicking on them, but after following multiple tutorials on "raycaster", I'm having trouble identifying where the issue lies. When I open my HTML file, all the objects are hidden, even though I've removed ...

Combining individual TypeScript files together

Recently, I encountered an issue with 2 typescript files: a.ts: let some : string = "some"; b.ts: console.log(some); Surprisingly, when compiling both files together by including them in the tsconfig or command line, there was no error about 'som ...

How to correctly deserialize dates in Angular 5

When working with Angular 5, I have encountered an issue where JSON data from an API is not properly deserialized into dates within an array. My model includes a definition like this: export interface ProcessDefinition { _id?: string; proces ...

fetch and modify data simultaneously in firebase

Is there a way to retrieve a value from a Firebase document and immediately update it? I am familiar with methods for updating documents and retrieving their values separately, but how can I accomplish both in one go? update firebase.firestore().collecti ...

The agent.add() function is malfunctioning, while console.log() is functioning properly

I'm currently working on integrating a bot using Telegram, Dialogflow, and Firebase. One particular function that I'm struggling with is as follows: function findDoc(agent){ const userId = request.body.originalDetectIntentRequest.payload.dat ...

Reorganize the workflow in Node.js by moving the business logic from the controller to the

As I delve into learning Node.js, I've encountered a challenge with code refactoring. After researching the best practices for code architecture in Node.js, I am eager to refactor my code. The current state of my code: user.controller.js const bcry ...

Handling asynchronous behavior in the context of conditional statements can be a challenging aspect of

Currently, this code section is passing undefined to if(customerWaiting >0). It's an async issue that I'm struggling to resolve. Despite my efforts and research on other threads, I can't seem to make this basic newbie question work. I&a ...

Clearing the canvas completely with CamanJS: a step-by-step guide

I need some help with my CamanJS photo editing app. Everything is working perfectly except for one issue - when a user uploads a new image and applies a filter, the canvas reverts back to the previously uploaded image. Even though I am using the revert() f ...

Using Cheerio with a Node.js bot

I am currently utilizing Cheerio to extract information from web pages in my .js files. However, I would like these files to automatically restart every 1 day to check for any new data. Instead of using setTimeout, which may not be efficient for managing ...

Connecting two JavaScript files without the use of HTML involves importing the first file into the second

Currently in my project, I have File1.js containing the essential functions, while File2.js houses additional functions that I prefer not to include in File1.js for easier editing purposes. I'm curious if it's feasible to call a function defined ...

What is the best way to transfer data from a parent component to a child component in ReactJs?

When dealing with nested react elements, how can you pass values from the parent element to a child element that is not directly inside the parent element? React.render( <MainLayout> <IndexDashboard /> </MainLayout>, document.b ...

Exploring the capabilities of Angular 2 and delving into inquiries regarding IIS

I'm diving into the world of Angular 2 as a beginner. Previously, I used to include JavaScript (like jQuery.js) in my HTML and then upload the finished page to my IIS website. Now that I'm learning Angular 2, I've had to install Node.js, NP ...

You can interact with our dropdown menu using the tab key, even when it is

We are looking to make our dropdown tabbable when expanded and non-tabbable when collapsed. We attempted using tabindex="-1" on the content inside the expandable div, but this resulted in it being non-tabbable even when expanded. Any suggestions on how t ...

Issues encountered during the configuration of Angular 8 Route (Auth) Guards

I recently attempted to incorporate Route Guards into my web application but encountered numerous errors along the way. Can anyone pinpoint where I might have gone wrong? My web app features various routes, one of which is a dashboard that requires protec ...