Verify if an Array includes a specific Property and connect it to a fresh Array

I have an array that I need to bind in a specific way:

const newData = json.map((c) => {
   return {
     "User Name": c.userName,
     Email: c.email,
     Groups: c.newArrGroups.map(a => a.name).toString(),
     Version: c.clientVersion
   };
});

The data stored in the variable json is passed from a function. Now, I need to check if the array has certain properties. I found a method to do this:

json.hasOwnProperty("userName")

I have two things to verify now. First - I need to check if a specific property exists in the array and remove it if it doesn't; Second - There could be arrays inside an array object. Is there a way to modify the code above to handle this scenario as well?

const newData = json.map((c) => {
  return {

    if(json.hasOwnProperty("userName")) {
      "User Name": c.userName, // Bind the property if it exists
    }

    Email: c.email,

    if(json.newArrGroups.hasOwnProperty("name")) {
      Groups: c.newArrGroups.map(a => a.name).toString(), // Check for nested arrays
    }
    
    Version: c.clientVersion
  };
});

Answer №1

Encountering a simple problem here. Take a look at my demonstration here.

// Example of JSON data
const json = [
    {
        userName: "JohnDoe",
        email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="204a4f484e0e444f45604558414d504c450e434f4d">[email protected]</a>",
        newArrGroups: [{ name: "Admin" }, { name: "User" }],
        clientVersion: "1.0.0"
    },
    {
        email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b111a151e551f141e3b1e031a160b171e55181416">[email protected]</a>",
        newArrGroups: [{ name: "User" }],
        clientVersion: "1.0.1"
    },
    {
        userName: "Alice",
        newArrGroups: [{ name: "Admin" }],
        clientVersion: "1.0.2"
    }
];

// Function for mapping the data
const newdata = json.map((c) => {
    const result = {};
    if (c.hasOwnProperty("userName")) {
        result["User Name"] = c.userName;
    }

    if (c.hasOwnProperty("email")) {
        result.Email = c.email;
    }

    if (c.hasOwnProperty("newArrGroups") && Array.isArray(c.newArrGroups)) {
        result.Groups = c.newArrGroups.map(a => a.name).toString();
    }

    if (c.hasOwnProperty("clientVersion")) {
        result.Version = c.clientVersion;
    }

    return result;
});

// Showing the result on the webpage
document.getElementById('output').textContent = JSON.stringify(newdata, null, 2);
<h1>Mapped Data</h1>
<div id="output"></div>

Give it a try and let me know how it goes! :)

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

Using TypeScript to access a specific key within an excluded readonly object literal

To ensure that the value assigned to BAR is one of the labels ('aa' or 'bb') corresponding to keys other than 'c' and 'd' in the read-only object FOO. const FOO = { a: { label: 'aa', value: ' ...

Learn how to refresh data using a specified ID from a separate component in Angular with a simple click event

I have a feature in my Angular2 application where a component loads responses upon button click events, fetching the data via Web API calls. The component also displays questions at the end of the template. My challenge is how to refresh this section with ...

Exploring the World of ESLint, Prettier, Typescript, and VScode Configuration

There is a common belief that Prettier is the preferred tool for formatting, while ESlint is recommended for highlighting linting errors, even though ESlint also has formatting capabilities. However, it should be noted that Prettier lacks certain advanced ...

Should ComponentFactoryResolver be utilized in an Angular 7 application?

I'm interested in developing an angular 7 web application that can load various components dynamically. I found a helpful resource on how to achieve this at this official documentation. However, I have some reservations about using ComponentFactoryRe ...

Locate consecutive characters in an array's string and swap them out

Here is an example array: arr=['Hello World', 'Bye World', 'Useless World'] I am looking to utilize JavaScript to identify consecutive characters that are the same ("ss") and substitute them with an asterisk (*) ...

Having trouble getting Angular 2 QuickStart to run with npm start?

When attempting to start my project with npm start, I encountered the following error: C:\angular2-quickstart>npm start > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="47262920322b2635756a36322e242c343326353307766 ...

Angular 2: focusing on input elements

Struggling with Angular 2 and a focus issue in your code? You're not alone. I'm facing a problem where I need to shift focus from input1 to input2 once the maxlength is reached. Currently, I am tracking key presses and comparing them to the set ...

Securing a definitive URL for a web application hosted on Azure Static Web App for long-term use

Currently, I am in the process of developing an Azure-based application. The setup I have so far consists of: The frontend being Angular v16 and hosted on an Azure Static Web Site (running on Linux) The backend utilizing an ASP.NET Core 7 Web API hosted i ...

What is the correct way to set up Typescript with external packages for Internet Explorer 11 using Babel 7 and Webpack 4?

After releasing a new version of our react app, we encountered an issue with IE11 complaining about the use of the let keyword. Upon investigation, we discovered that upgrading the query-string package from version 5.1.0 to 6.4.0 introduced the usage of th ...

Storing Angular 4 Http Post response data in an object

I'm currently working with Angular 4 in conjunction with an Asp.net web API. I am facing difficulties in reading the properties of my response. This is how my response appears: https://i.stack.imgur.com/NDJCo.png Here is my post request: postLogi ...

Oops! The module "rxjs/Subject" seems to be missing the exported member "Subject"

Here is the code I'm working with: import { Subject } from 'rxjs/Subject'; Upon importing this, an error occurs: rxjs/Subject" has no exported member 'Subject'. I am unable to fix this issue. Does anyone have a solution? ...

Using Angular2 Router can sometimes result in template "overwrites"

My routing implementation seems to be causing issues in my app. When I click the Login button, it should direct me to a new login page. However, instead of navigating away from the main page (VehicleComponent), it creates the login page within the main pag ...

Unable to retrieve nested objects from HTTP Response

After receiving data from a HTTP Response, I am trying to access and display it in my template. However, despite storing the data into a component variable, I am encountering issues when trying to access specific properties of the object. { "files": [ ], ...

Row index retrieval in Datatable is not possible following a search operation

I have successfully created a datatable and can retrieve the row index of the data before any search action is performed. dataArray=[ [1, "Name1"], [2, "Name2"], , [3, "Name23"], ]; var table = $('#tblName').DataTable( { ...

Repeating percentages displayed in a progress bar

I created a responsive progress bar, but the progress values are repeating. I only want the central value to be displayed. Any suggestions on how to fix this issue? DEMO <div id="tab1"> <dx-data-grid class="tableTask" [dataSource]="datas" ...

Why is the observable I'm utilizing in this Angular 11 component returning as undefined?

Currently, I am working on implementing a promotions feature for an Angular 11 e-commerce application. I have developed a service that sends a get request and retrieves a JSON file containing the campaign's information. The Service: import { Injectab ...

Creating a global pointer to an array of structures

I found this code block that I am having issues with: #define N 100 //starting size of the array int is_full(VERTEX *arr); int add_vertex(char *name); int print_degree(int ID); int _get_vertex(int ID); VERTEX *resize_array(VERTEX *vertex_array,int new_s ...

What is the method for dynamically altering attributes using a directive?

I am currently working on dynamically assigning attributes to HTML tags (such as Select, Button, or Input) within a switch statement. However, I'm a bit stuck and would appreciate any better ideas or suggestions you may have. My goal is to identify w ...

Updating an Angular component: identifying the whole component as needing refresh

Is there a simpler method to set the dirty property at the component level without using ng-model and ids? I know that these can be used to access properties like dirty and pristine as stated in the Angular documentation. I have a component that contains ...

How to open a PDF file in a new tab using Angular

Within my Angular 12 application, I am seeking to enable users to "view" a PDF file stored locally in the application within a new tab on Google Chrome. Currently, when implementing the code below in HTML, the file downloads rather than opening in a new ta ...