Is there a clever method to transform the property names of child objects into an array of strings?

I have a similar object that looks like this:

{
    "name":"sdfsd",
    "id":1,
    "groups":[
        {
            "name":"name1",
            "id":1,
            "subGroups":[..]
        },
        {
            "name":"name2",
            "id":21,
            "subGroups":[..]
        }
    ]
}

My goal is to create an array with the following structure:

[
   {
      "name":"name1",
      "id":1
   },
   {
      "name":"name2",
      "id":21
   }
]

Instead of using a loop to manually create the array, I am wondering if there is a more elegant solution in ES6.

Answer №1

If you want to simplify the code, you can do it in the following ways:

const groups = this.obj.groups.map( ({name, id}) => ({name, id}) );

Alternatively, you can create a separate function for mapping like this:

const getNameId = ({name, id}) => ({name, id});
const groups = this.obj.groups.map(getNameId);

This code makes use of various ES6 features including:

  • The map() function which allows for mapping over an existing array and creating a new one immutably.
  • Destructuring objects as function parameters --> ({name, id}) =>
  • Object shorthand notation --> => ({name, id})
  • Point free notation - a feature favored by functional programming enthusiasts.

Answer №2

Utilizing the .map() method on arrays:

const newGroups = myData.groups.map(group => ({ groupName : group.name, groupId : group.id }) );

Answer №3

a simple ES6 method:

const elements = this.obj['elements'].map( ({id, name}) => ({ id, name }) );

Alternatively, for a more concise version using spread:

const elements = this.obj['elements'].map( ({categories, ...elements}) => (elements) );

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

Is there Polyfill Compatibility for Custom Elements in Angular 9?

When it comes to polyfilling support for custom elements created with Angular, there are various recommendations available. This demo demonstrates that adding the following polyfill in polyfills.ts works: import '@webcomponents/webcomponentsjs/custo ...

Angular and Spring Boot integration with Apereo CAS application

For my current project, I am building an application with Angular6 for the frontend and spring boot for the backend. Initially, all APIs in my backend are open to everyone, accessible via URLs like localhost:8080/api/get_data from the frontend. However, I ...

The Typescript generics are unable to be assigned to type T

Take a look at my code snippet: interface IDoc { doSomething(): void } class IDocFoo implements IDoc { doSomething(): void { console.log('Do doSomething'); } } class IDocFactory { getIDocInstance<T extends IDoc>(): T { re ...

Leverage Angular2 components within Angular4 framework

Would it be possible to utilize angular2 components in angular4 projects? Specifically, I am interested in using a chart generation library from . However, it seems that the dependencies of this library are not compatible with my application. Are angular2 ...

How to handle an empty data response in Angular 2's HTTP service

My ASP.NET web API has a simple method with the following test results: $ curl localhost:5000/Api/GetAllQuestions [{"questionId":0,"value":"qqq","answers":[{"answerId":25,"value":"qwerty"}]}] However, I am encountering an issue in my Angular 2 HTTP serv ...

Is it possible to utilize useEffect for verifying the existence of the user token within the localStorage?

I am in the process of developing a web application that requires authentication. I am wondering if it is effective to create a private route by adding a condition in the useEffect hook of one of my pages. The idea is to check if a token is present before ...

What is the best way to send the body in a GET request using Angular 2+?

My API's GET method is located at "http://abc/abc" Typically, the GET method includes parameters as get(url, options), with only two arguments. However, in my scenario, I need to include a body with the request. The body structure is as follows: { ...

The Angular component router-outlet is not recognized as a known element

I have encountered an error message: 'router-outlet' is not a known element: 1. If 'router-outlet' is an Angular component, then verify that it is part of this module. 2. If 'router-outlet' is a Web Component then add ...

Unable to associate Interface with HTTP response

When I run the following code in Chrome console, I get an error: ERROR TypeError: t.json(...).map is not a function. However, both ng serve -prod and ng test --sm=false work fine. My goal is to map the result to the model in Interface and display it in HT ...

The bidirectional bindings within the component are malfunctioning

I just started learning Angular and I'm currently working on a small project. After following tutorials on two-way bindings, I attempted to implement it in my project. However, when I try to set values in the HTML for my component, it doesn't see ...

What is the best way to save code snippets in Strapi for easy integration with SSG NextJS?

While I realize this may not be the typical scenario, please listen to my situation: I am using Strapi and creating components and collections. One of these collections needs to include code snippets (specifically typescript) that I have stored in a GitH ...

Exploring Objects with Union Types in TypeScript

Looking to iterate through an object that combines two interfaces. interface Family { cat: string; age: string; family: string; lastYearFamily: string; } interface Model { cat: string; age: string; ...

Encountering errors while working with React props in typing

In my application, I am utilizing ANT Design and React with 2 components in the mix: //PARENT const Test = () => { const [state, setState] = useState([]); function onChange( pagination: TablePaginationConfig, filters: Record<string, ...

Browser inspect tool is failing to hit breakpoints when using USB-connected device

While troubleshooting my Ionic Capacitor application on a USB connected device, I noticed that my browser dev-tools (Chrome, Edge, Firefox) are not hitting my breakpoints in the source code. Interestingly, when I run the application on ionic serve, everyt ...

Create a visual representation of progress over time by utilizing a single horizontally stacked bar chart with ChartJS

Can chartjs be configured to show horizontal stacked bars for continuous data over time? It's more of a progress visualization than a traditional chart. I am struggling to display multiple data points per label and have them shown as one bar. I have ...

What causes an error when the App is enclosed within a Provider component?

What is causing the error when wrapping the App in Provider? Are there any additional changes or additions needed? Error: "could not find react-redux context value; please ensure the component is wrapped in a @Provider@" import React from ' ...

What is the method for extracting date of birth data from .NET to Angular?

Struggling to fetch the date of birth from the database where it has been stored. After searching through multiple resources online, I am still unsure about how to accomplish this task. export class DetailsEmployeeComponent implements OnInit{ employeeD ...

The container is not adjusting to the screen size correctly and the flex-direction: row is not functioning as

Struggling with setting up a basic layout in Angular for my application. While I have experience with Angular, the actual HTML/CSS design is new to me. No matter what I try, I can't seem to get this container to take up the whole screen width. Variou ...

Guide on accessing appsettings file in Angular 5's app.module

Greetings! As I dive into developing a web application with Angular 5, I am faced with the challenge of reading values from appsettings.json and utilizing them in app.module.ts. Inside my app.module.ts file, within the imports section, resides the followin ...

Encountering an error in resolving symbol values statically within the Angular module

Following a helpful guide, I have created the module below: @NgModule({ // ... }) export class MatchMediaModule { private static forRootHasAlreadyBeenCalled: boolean = false; // This method ensures that the providers of the feature module ar ...