Leveraging the power of map function to transform arrays in Javascript

I have a JSON object structured like this:

{
   "id": 12,
   "firstName": "Mohamed",
   "lastName": "Sameer",
   "contactgroups": [
      {
         "id": 16,
         "group": {
            "id": 4,
            "groupname": "Angular"
         }
      },
      {
         "id": 19,
         "group": {
            "id": 5,
            "groupname": "React"
         }
      },
      {
         "id": 20,
         "group": {
            "id": 6,
            "groupname": "Node"
         }
      }
   ]
}

Desired output format:

{
   "id": 12,
   "firstName": "Mohamed",
   "lastName": "Sameer",
   "groups": [4, 5, 6] // retrieved from 'group' object with id and groupname //
}

I am looking to accomplish this using JavaScript methods without resorting to for loops.

Can it be achieved using the map method?

This was my attempt:

const data = {
   "id": 12,
   "firstName": "Mohamed",
   "lastName": "Sameer",
   "contactgroups": [
      {
         "id": 16,
         "group": {
            "id": 4,
            "groupname": "Angular"
         }
      },
      {
         "id": 19,
         "group": {
            "id": 5,
            "groupname": "React"
         }
      },
      {
         "id": 20,
         "group": {
            "id": 6,
            "groupname": "Node"
         }
      }
   ]
}

const finalData = data.contactgroups.map(x => ({
   id: data.id,
   firstName: data.firstName,
   lastName: data.lastName,
   groups: [x.group.id]
}));

console.log(finalData);

Answer №1

Consider trying out something similar to the following code snippet. By the way, I've utilized ES6 syntax here.

let user = {
   "id": 12,
   "firstName": "Mohamed",
   "lastName": "Sameer",
   "contactgroups": [
      {
         "id": 16,
         "group": {
            "id": 4,
            "groupname": "Angular"
         }
      },
      {
         "id": 19,
         "group": {
            "id": 5,
            "groupname": "React"
         }
      },
      {
         "id": 20,
         "group": {
            "id": 6,
            "groupname": "Node"
         }
      }
   ]
};

let groupIds = user.contactgroups.map(item=>(item.group.id));

let modifiedUser = {
    "id": user.id,
   "firstName": user.firstName,
   "lastName": user.lastName,
   "groupIds": groupIds
}

Answer №2

Utilize destructuring assignments to create a new object containing mapped IDs.

function getModifiedObject({ id, firstName, lastName, contactgroups: groups }) {
    return { id, firstName, lastName, groups: groups.map(({ group: { id } }) => id) };
}

var data = { id: 12, firstName: "Mohamed", lastName: "Sameer", contactgroups: [{ id: 16, group: { id: 4, groupname: "Angular" } }, { id: 19, group: { id: 5, groupname: "React" } }, { id: 20, group: { id: 6, groupname: "Node" } }] };

console.log(getModifiedObject(data));

Answer №3

Here is the solution to your query:

let userData = {
      id : data.id,
      firstName: data.firstName,
      lastName: data.lastName,groups: data.contactgroups.map(y=> y.group.id)}

console.log(userData);

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

Step-by-Step Guide on Retrieving Filtered Data using React Context API

Currently, I am in the process of developing a dashboard application using React.js, React Context API, and ApexCharts. The app will visualize a 1000-length JSON data on 7-8 different charts, along with 6-7 variable filters. Overview of the App Structure: ...

Working with DateTime formatting in JSON and JODA librarires

I'm currently working on developing a Restful webservice using Spring boot and JPA. Everything seems to be functioning correctly, except for the time format in the JSON response which is not formatted as desired. "created": 1440327152688, "upda ...

Mapping an Optional<Enum> with @RequestBody in Spring's MVC

I am working on a rest controller that includes the following method: @RequestMapping(value = "", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity<?> add(@Valid @RequestBody MyModel myModel, ...

A guide to displaying the date retrieved from a JSON data file API request using JavaScript

How can I display the date from a JSON data file API call using JavaScript? I am facing difficulty in showing the date on the dashboard display page. I am utilizing JavaScript with async-await for calling the API, and Bootstrap 4 for design. The function ...

Having trouble connecting JSON data to TreeTable Js through knockout.js?

I found a helpful plugin called TreeTable that I am using. You can check it out here: <table id="example-basic"> <thead> <tr> <th>Name</th> <th>Status</th> <th>id</th> ...

Utilizing React Hooks to toggle the aria-expanded boolean value

I'm presently focusing on enhancing accessibility for a web application utilizing React and Ant Design's Select component. The value of aria-expanded is currently set to 'false' string. My goal is to utilize React's useState to to ...

Embed fashion and graph elements into a CSV document (generated from <script>)

Encountering an issue with my code. I am looking to export an HTML table to a CSV file (specifically Libre Office Calc, regardless of csv, xls or xlsx format, as long as it runs on a Linux Server). Found a script online that works well after some modificat ...

The function IdleProvider.windowInterrupt does not exist

I'm currently attempting to set up the most basic implementation of ng-Idle in node.js on my development environment. To achieve this, I have utilized the minimal sample provided at this link, and have integrated it into a previously functional minima ...

What is the most effective way to monitor the duration of video playback?

Whenever a user watches a video, I aim to initiate 2 AJAX calls. The first call should trigger when the user finishes watching the entire video or if the time played is equal to or greater than the duration of the video (considering users may rewind). time ...

External CSS File causing improper sizing of canvas image

I have been working on implementing the HTML5 canvas element. To draw an image into the canvas, I am using the following javascript code: var img = new Image(); var canvas = this.e; var ctx = canvas.getContext('2d'); img.src = options.imageSrc; ...

Experiencing port accessibility problems while running two separate ReactJS frontends on a Google Cloud virtual machine

As I continue to test various versions of a ReactJS frontend on a Google Cloud VM instance, I have successfully configured the first version by adjusting the "scripts" section in the package.json file to start: "react-scripts start --host 0.0.0.0". However ...

Concealing a Column within a Hierarchical HTML Table

Can anyone guide me on how to hide multiple columns using jQuery with the ID tag? I've tried implementing it but it doesn't seem to work. I also attempted to switch to using Class instead of IDs, but that didn't solve the issue either. Any h ...

Avoiding unnecessary Ajax requests using pushstate for pagination

I encountered an issue with ajax pagination using the HTML API Pushstate. Here is the code I am working with: <ul class="small"> <li> <p>a</p> </li> </ul> <ul class="paging"> <li><a ...

Automatically scroll to each div or element on the page

Can anyone help me with implementing an auto scroll to each div or element when the user scrolls using the mouse? Here is the scenario: Imagine this structure of the page... <div id="main-wrap"> <div class="my-div-1"> <p>here goes ...

I keep receiving a 400 (Bad Request) error when trying to delete with my REST API

I've successfully created an API and have managed to make POST and GET requests work flawlessly. However, I'm facing some trouble with the DELETE request. Every time I try to execute it, I encounter a 'DELETE http://localhost:3000/api 400 (B ...

Ways to display a price near a whole number without using decimal points

Currently, I am working on an ecommerce project where the regular price of an item is $549. With a discount of 12.96% applied, the sale price comes down to $477.8496. However, I want the sale price to be displayed as either $477 or $478 for simplicity. Yo ...

Duplicating a div element using jQuery .load

I am facing an issue where attempting to refresh a div results in the duplication of the div, creating one inside the other. The current setup involves the use of jQuery, Struts2, and the Struts2 jQuery plugin for the view. Current Behavior: <div id=" ...

Implementing user authentication in Node.js using the Passport library alongside Express framework

An interesting article caught my attention on Scotch.io: https://scotch.io/tutorials/easy-node-authentication-linking-all-accounts-together Although it was published back in January 2014, Chris demonstrates how to check the value of req.user within the p ...

Failed to load TypeScript file or similar issue

Whenever I attempt to generate a TypeScript file from a partial view (MVC .NET) that is loaded through a rest call and then appended to a div element, I encounter an error in my console. The error message reads: Uncaught ReferenceError: xyz is not defined ...

Concealing external scripts on specific webpages

In my HTML template, I have integrated a third-party JavaScript code that provides a chat option. This script is included in my header.html so that it appears on all pages. However, I do not want this chat option to display on the login page. I want it to ...