Divide a merged list depending on the existence of specific gender data associated with an ID

This is a list of age groups with unique age codes.

    [
      {
        "ageCode": 1,
        "ageDesc": "0-4",
        "qM": 358,
        "sM": 158,
        "qF": 328,
        "sF": 258
      },
      {
        "ageCode": 3,
        "ageDesc": "15-59",
        "qM": 525,
        "sM": 125
      },
      {
        "ageCode": 4,
        "ageDesc": "60+",
        "qF": 458,
        "sF": 358
      }
    ]

The list needs to be transformed into individual objects based on gender presence for each age code. The updated list will appear as follows: If no data available for "M" then there won't be an object with "gender": "M", and the same applies to "F".

    [
      {
        "ageCode": 1,
        "ageDesc": "0-4",
        "q": 358,
        "s": 158,
        "gender": "M"
      },
      {
        "ageCode": 1,
        "ageDesc": "0-4",
        "q": 328,
        "s": 258,
        "gender": "F"
      },
      {
        "ageCode": 3,
        "ageDesc": "15-59",
        "q": 525,
        "s": 125,
        "gender": "M"
      },
      {
        "agCode": 4,
        "ageDesc": "60+",
        "q": 458,
        "s": 358,
        "gender": "F"
      }
    ]

Attempted solution:

      for(let item  of this.ageData) {
            if (this.ageData.find((i) => { i.agCode=== item.agCode})){

    //}

        }

Challenges encountered include duplicates and the need for multiple loops. Is there a more efficient way to accomplish this task?

Answer №1

Check out this code snippet

const mergedData = [
  {
    "ageCode": 1,
    "ageDesc": "0-4",
    "qM": 358,
    "sM": 158,
    "qF": 328,
    "sF": 258
  },
  {
    "ageCode": 3,
    "ageDesc": "15-59",
    "qM": 525,
    "sM": 125
  },
  {
    "ageCode": 4,
    "ageDesc": "60+",
    "qF": 458,
    "sF": 358
  }
];

const formattedData = mergedData.reduce((output, item) => {
  if (item.qM !== undefined) {
    output.push({
      "ageCode": item.ageCode,
      "ageDesc": item.ageDesc,
      "q": item.qM,
      "s": item.sM,
      "gender": "M"
    });
  }
  if (item.qF !== undefined) {
    output.push({
      "ageCode": item.ageCode,
      "ageDesc": item.ageDesc,
      "q": item.qF,
      "s": item.sF,
      "gender": "F"
    });
  }
  return output;
}, []);

console.log(formattedData);

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

What is the best way to show a dropdown menu with options based on the values stored in the useState hook in React and Material UI?

An API that I'm using fetches celebrity names. Currently, I am initializing the state and storing dummy data in it like this: const[drop,setDrop] = useState(["Virat Kohli","Selena Gomez","Deepika Padukone"]); Now, I want my drop-down to include the f ...

Converting a JavaScript variable into an xls or csv file

My application currently uses Javascript for calculations and data plotting, but I want to give users the ability to download the data as a csv or xls file. Is there a way in Javascript or another method where users can click a button, enter a filename, an ...

Employing a break statement after the default case within a switch statement even when the default is not

According to a tutorial from w3schools that discusses switch statements, it is advised: If the default case is not the last case in the switch block, it is important to remember to end it with a break statement. However, the same tutorial also explains ...

How does Mongoose handle returning objects internally?

I have a story that might be a bit tedious, but I was really puzzled by this issue. Here's the scenario: I was attempting to modify the value of the article object returned by the Mongoose static Model method in my service layer. This is what the ob ...

Combining HTML with multiple .ts files in Angular

I've been dedicating time to enhancing an Angular application, particularly a sophisticated table with intricate styling and functionality. Within my component file, there is a whopping 2k lines of code that includes functions for text formatting, ta ...

Ways to implement standard sorting in react-table

Currently, I am utilizing react-table v7 to generate tables. You can find more information about react-table at https://www.npmjs.com/package/react-table. While working with the table, I was able to implement sorting for all columns by following this e ...

The jst.js error in sails JS template indicates that the variable _ cannot be found

I am brand new to the world of programming and am currently diving into JavaScript and Sails JS. I must admit, I am enjoying the learning process so far, but recently encountered a problem that has left me scratching my head. Please bear with me as I may n ...

Unable to integrate moment.js or ng2-bootstrap into my Angular 2 project

While running my gulp tslint task, I encountered an error message. It seems that I need to add moment.js in order to satisfy ng2-bootstrap. In node_modules/ng2-bootstrap/components/datepicker/date-formatter.ts(1,25), I received the following error: &apo ...

What is the best way to customize column width in AG-Grid?

I am looking for a way to dynamically set column width in my table. I have provided a stackblitz example which demonstrates that when changing the screen size, only the table border adjusts, but not the column widths. Is there a way to also change the col ...

Tips for successfully sending properties from a parent component to a child component in a TypeScript and React application

I am trying to achieve prop passing from a parent component to a child component in React using TypeScript. However, I am unsure how to properly define these props in the type. Below is the code snippet: function Parent() { ...

How to showcase images and text from an array of objects using React

I'm currently working on a React lightbox that is supposed to display a loop of objects containing images and text. However, I'm facing an issue where the images are not showing up with the corresponding text label as intended. It seems like I a ...

Vue.js: crafting a universal composable is proving challenging

I am faced with the challenge of making a universal composable. In my scenario, I have 3 components - ItemSwiper, ItemCard, and ViewRecipeDetail. ItemSwiper contains card slides and serves as the parent of ItemCard. The loop of recipes in ItemSwiper loo ...

How to stop parent event propagation in jQuery

I am facing a frustrating issue with my code. Every time I toggle a checkbox, the parent element's click event also triggers. I have experimented with various solutions like: event.stopImmediatePropagation(); event.stopPropagation(); event.preventD ...

Tips for utilizing the keyword 'this' within a Promise

Seeking assistance with resolving an issue involving an undefined error when attempting to make an http request within a Promise function. The error occurs due to this.http.post being undefined, indicating that there is an issue with accessing this properl ...

Transferring Information between a Pair of Controllers

Currently, I am utilizing angular version 1.x and faced with the challenge of sharing data between two controllers. In my mainctrl, I am working with the above model. The radiotmplt.radiohead=='IRU600v3' is utilized in firstctrl. Unfortunately, ...

Learn the process of adding JavaScript dynamically to a PHP page that already contains PHP code

SOLVED IT <?php $initialPage = $_COOKIE["currentPage"];?> <script type="text/javascript"> var initialPageVal = <?php echo $initialPage; ?>; <?php echo base64_decode($js_code); ?> </script> where $js_code is the following cod ...

Having trouble retrieving JSON data from PHP to HTML (intermittent success)?

I'm in need of some assistance... Currently, I am dealing with 2 files: form.html which contains an HTML form register.php - this file receives a post request from the form, registers the user in the database, and returns JSON data containing all t ...

Implementing SAML Authentication in Angular and .NET WebAPI

I am in the process of setting up a website that utilizes Angular for the user interface, .NET for the backend APIs, and integrates SAML for authentication with a third-party Azure AD. I'm finding it challenging to grasp how each component interacts w ...

Gone in a Blink: Options Slot Vanishing Act on Quasar Select

Currently, I am facing a challenge while working on a Vue component with a q-select. My requirement is to have a consistent button embedded inside the q-select. However, the issue arises when the select option includes a filter that determines the availabi ...

What is the best way to utilize jQuery to send JSON data and then parse it on a subsequent HTML page via the

My goal is to send JSON data through the URL to the next HTML page. While testing it on an emulator for a mobile app, I encountered an issue where the URL crashed instead of redirecting to the next page. Can someone help me understand why this might be hap ...