How can you merge arrays in Angular based on their unique names?

Is there a way to combine objects within the same array in Angular based on their names?

[{
    "name":"Navin",
    "id":"1"
    },
    {
    "name":"Navin",
    "mark1":"98"
    },
    {
    "name":"Navin",
    "mark2":"50"
    }
    ]

The desired output should be:

[{
"name":"Navin",
"id":"1",
"mark1":"98",
"mark2":"50"
}]

Answer №1

Feel free to utilize any of the following code snippets.

const sampleObject = [{
  "name": "Jessica",
  "id": "1"
},
{
  "name": "Jessica",
  "score1": "95"
},
{
  "name": "Jessica",
  "score2": "78"
}
];
console.log([sampleObject.reduce(function(result, current) {
  return Object.assign(result, current);
}, {})]);

 console.log([sampleObject.reduce(((r, c) => Object.assign(r, c)), {})]);

console.log([Object.assign({}, ...sampleObject)]);

Answer №2

To properly structure your information, you can utilize the following function:

let studentInfo = [
  {
    "name":"Navin",
    "id":"1"
  },
  {
    "name":"Navin",
    "mark1":"98"
  },
  {
    "name":"Navin",
    "mark2":"50"
  }
];

function formatStudentData(studentInfo) {
  const uniqueNames = [];
  const formattedData = [];
  studentInfo.map(info => {
    if (uniqueNames.includes(info.name)) {
      formattedData.map(fData => {
        if (fData.name === info.name) {
          Object.keys(info).map(dataKey => {
            if(dataKey !== 'name') {
              fData[dataKey] = info[dataKey];
            }
          });
        }
      });
    } else {
      uniqueNames.push(info.name);
      formattedData.push(info);
    }
  });
  
  return formattedData;
}

let structuredStudentData = formatStudentData(studentInfo);
console.log(structuredStudentData);

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

When trying to access the "form" property of a form ElementRef, TypeScript throws an error

I've encountered an issue with accessing the validity of a form in my template: <form #heroForm="ngForm" (ngSubmit)="onSubmit()"> After adding it as a ViewChild in the controller: @ViewChild('heroForm') heroForm: ElementRef; Trying ...

Error message: The attempted import failed because ' is not exported from the module

I am facing an issue with resolving my problem. In a file named lama.d.ts, I have declared a class using the following code: export declare class lama { // code here } After that, I tried to import this class in another file within the same folder ...

Dynamic Angular select options with ngFor causing cascading changes in subsequent selects

In my Angular 5 project, I am attempting to create a set of three <select> elements using *ngFor. I came across a helpful thread on Stack Overflow that provided some guidance (check it out here). However, I've encountered an issue where the sele ...

Adding an image to a Select Option label in React: A simple guide

As a newcomer to React, I am experimenting with creating a drop-down menu that includes images in the labels. My approach involves using a function to gather values from a map and construct an id: label pair to display as options in the drop-down. Both the ...

Implementing a props interface for conditions in styled components within a React application using Typescript

This specific component is created using React along with the "styled components" library to manage user input. In the case of invalid user input, the corresponding styles should be displayed as shown below (class invalid). Although this example functions ...

Accept an empty string as the defaultValue, but disallow it during validation using Zod, react-hook-form, and Material UI

Currently, I am working with material ui components alongside react-hook-form and zod validation in my project. One of the challenges I encountered is with a select field for a bloodType: const bloodTypes = [ "A+", "A-", "B+", ...

Guide to retrieving the previous URL in Angular 2 using Observables

Can someone help me retrieve my previous URL? Below is the code snippet I am working with: prev2() { Promise.resolve(this.router.events.filter(event => event instanceof NavigationEnd)). then(function(v){ console.log('Previous ' ...

Error Message: "Unable to access property 'proposta_usuario' of undefined in Angular 2 Data Binding"

I've been encountering some issues while trying to bind data from an input in Angular 2. Below is the HTML code snippet: <input type="text" class="animated bounceIn input-proposta" placeholder="Enter your proposal" [(ngModel)]="propo ...

Is there a way to prompt the compiler to generate an error when a type cannot be set to `undefined`

I'm working with a type called ILoadedValue<TValue>, which acts as a wrapper for types that can potentially be undefined. However, I want to prevent situations where TValue cannot be undefined, as it's more efficient to use the actual value ...

Having trouble configuring custom SCSS Vuetify variables with Vue 3, Vite, Typescript, and Vuetify 3

Having some trouble with custom variables.scss in Vuetify. Looking to make changes to current settings and added my code on stackblitz. Check it out here Been going through Vuetify documentation but can't seem to pinpoint the issue. Any assistance w ...

Verifying Angular (2+?) Compatibility: Opening and Closing Material mat-menu on Hover [GUIDE]

After extensive research, I tried various methods to hover a material menu to display its options. However, the solutions I came across were either too complicated or ineffective. Therefore, I decided to develop my own solution by combining elements of e ...

Safari (mac) experiencing issues with loading material icons properly on initial attempt

Upon my initial visit to the website, I noticed that the font appeared distorted. https://i.sstatic.net/BtUxI.png However, when I right-clicked and chose "reload page", the fonts were displayed correctly. https://i.sstatic.net/3XUcA.png This issue seem ...

Service for language translation in Angular

I attempted to use an angular translation service to translate English words to Chinese using a key-value mapping approach, but unfortunately, I was unsuccessful. Does anyone have any suggestions? Here is the JSON mapping: "At most {{ number }} wrods ...

Utilizing TypeScript to spread properties onto a component and destructure them from within components

I'm trying to optimize my use of props spreading and destructuring when working with components. Currently, I spread my props in this manner: <RepositoryItem {...node} /> Then, within the component, I destructure the props like so: interface ...

Struggling to establish object notation through parent-child relationships in Angular 2

Hi there, I am new to Angular and JavaScript. Currently, I am working on achieving a specific goal with some data. data = ['middlename.firstname.lastname','firstname.lastname']; During the process, I am looping through the .html usin ...

Incorporating AWS-Cognito into Angular 2

I'm currently diving into the world of building web applications using Angular and AWS. My initial focus is on setting up authentication with AWS-Cognito. However, I've encountered some hurdles while trying to import and utilize the AWS-Cognito S ...

Encountered an issue trying to access undefined properties while reading 'PP'

I am trying to showcase the data retrieved from my JSON file. Here is a glimpse of the information stored in the JSON => Within DTA > PP , I am specifically interested in displaying the variable NOMFAMILLE. An error message has caught my attentio ...

What could be causing my items to appear twice and as blank elements?

I'm feeling a bit lost here as to why my code isn't functioning correctly. For some reason, it's not displaying the predefined items that I've set up. Any guidance or assistance would be greatly appreciated. Dealing with Angular errors ...

Can you tell me if it's a problem that I can view the application structure from the console's source window?

I have been asking around trying to find the answer to the question "what are the implications of being able to see the project structure in the source window of a browser?". Unfortunately, I have not received a satisfactory response yet, which is why I am ...

The Vue event was triggered, however there was no response

My current project consists of a Typescript + Vue application with one parent object and one component, which is the pager: //pager.ts @Component({ name: "pager", template: require("text!./pager.html") }) export default class Pager extends Vue { ...