Reconfigure an ancestral item into a designated key

I have a single object with an array of roles inside, and I need to transform the roles into an array of objects. See example below:

Current Object:

displayConfiguration: {
  widgetList: {
    widgetName: 'widget title',
    entityType: 'Asset',
    roles: [202]
  },
  addIcon: {
    fileName: '',
    fileDownloadUri: ''
  },
  displayInfoIcon: {
    visible: true,
    summaryText: 'info icon text'
  },
  useFilter: true
}

Expected Object:

displayConfiguration: {
  widgetList: {
    widgetName: 'widget title',
    entityType: 'Asset',
    roles: [
      {
        id: 202
      }
    ]
  },
  addIcon: {
    fileName: '',
    fileDownloadUri: ''
  },
  displayInfoIcon: {
    visible: true,
    summaryText: 'info icon text'
  },
  useFilter: true
}

Answer №1

const setup = {
  componentList: {
    componentName: 'component name',
    moduleType: 'Module',
    permissions: [104]
  },
  addButton: {
    fileName: '',
    fileLink: ''
  },
  displayHelpIcon: {
    active: true,
    infoMessage: 'helpful message'
  },
  applyFilter: true
}

const result = {
  ...setup, 
  componentList: {
    ...setup.componentList,
    permissions: setup.componentList.permissions.map(x => ({id: x}))
  }
  
}

console.log(result)

Transforming arrays using the map function is a simple and effective method.

Answer №2

One way to achieve this is by using the .map() function, which will iterate through each element and transform your number into the desired object.

const displayConfiguration = {
  widgetList: {
    widgetName: 'widget tiltle',
    entityType: 'Asset',
    roles: [202]
  },
  addIcon: {
    fileName: '',
    fileDownloadUri: ''
  },
  displayInfoIcon: {
    visible: true,
    summaryText: 'info icon text'
  },
  useFilter: true
};

const roles = displayConfiguration.widgetList.roles;
displayConfiguration.widgetList.roles = roles.map(role => {
 return {
  id: role
 }
})

console.log(displayConfiguration);

The map function generates a new array with the results of applying a specified function to each element in the original array.

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 it possible to add a click handler function to a dynamically generated link in Vue?

When working with Vue components, I receive dynamic messages from the server: module.exports = { data() { return: { windowText: '' } }, methods: { showCancelEntrieWindow(){ this.$http.post('/page', {'number& ...

Adding a character to an AngularJS textbox

I am attempting to add the "|" Pipe symbol to a textbox when a button is clicked, using this function. $scope.appendPipe = function(){ var $textBox = $( '#synonyms' ); $textBox.val($textBox.val()+'|'); //textBox ...

The issue of why iterating over an array of objects does not function properly in React JS

P.S: I have made some modifications to the code below. Extracting the doctor's value from JSON data, updating the state, and then mapping it to print out the values. Initially, there is only one doctor, but in the future, there could be more than one ...

Is Typescript capable of converting ES6 code to ES5 during transpilation?

Currently, I'm in the process of developing an application utilizing Angular 2 and TypeScript. My goal is to incorporate a JavaScript method, specifically 'filter' for arrays, that is compatible with IE 11+, Chrome 45+, and other similar bro ...

Easy selector for choosing jquery css backgrounds

Here is a simple background selector that I created. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <hea ...

What are the steps to take in order to successfully deploy an Express server on GitHub Pages?

I heard that it's possible to host an Express server on GitHub Pages, but I'm not sure how to do it. Is the process similar to deploying a regular repository on GitHub Pages? ...

Getting permission for geoLocation service on iOS in Ionic: A step-by-step guide

I have recently developed a social media application that utilizes geoLocation services. The app is built with Ionic 4 and has a Firebase backend. While the GeoLocation services are functioning properly on Android devices, users of iOS are not being prompt ...

Is there a way to retrieve a singular value from various select options sharing the same name within a single form?

I am facing an issue with my code where only the value assigned to the last select option panel is being saved in the database table. I need assistance as it was working well initially but for some reason, it's not functioning correctly now. <?php ...

Using a loop to chain jQuery's .when().then() method and ensuring a fixed final call at the end of the

The solution that closely matches my issue can be found at One common use case for .then is chaining ajax requests: $.ajax({...}).then(function(){ return $.ajax({...}); }).then(function(){ return $.ajax({...}); }).then(function(){ retu ...

Analyzing various field data collectively

Is there a way to use jQuery to compare multiple input field values and trigger an alert message saying 'There are similar values' if any match is found? <input value="111"> //similar <input value="222"> <input value="111"> //s ...

Adding a break in a CardHeader element subtitle in MaterialUI using ReactJS

I have been working with older Material UI components (Version 0.20.1). Below is an excerpt of my code: return( <> <Card> <CardHeader actAsExpander={true} showExpandableButton={true} title = {user.name} ...

Creating custom shaders for YouTube videos within a Three.js userscript

I want to add a shader effect to YouTube videos. My current approach involves using Three.js to implement a shader on a video. Specifically, I am trying to adapt this example of applying a shader to a video (code available here) into a Tampermonkey usersc ...

Using JavaScript, create a set of buttons within a div element and implement

$(document).ready(function() { $('#b1').click(function() { $('#uch').toggle("slow"); }); $('#b2').click(function() { $('#uch2').toggle("slow"); }) }) Although I'm not a program ...

Struggling with establishing recognition of a factory within an Angular controller

I am currently facing an issue while trying to transfer data from one controller to another using a factory in Angular Seed. My problem lies in the fact that my factory is not being recognized in the project. Below is my snippet from app.js where I declare ...

Encountering error while attempting POST request in POSTMAN - "Unable to modify in restricted editor."

I'm facing a bit of a dilemma here. I can't seem to figure out how to make my editor in Postman stop being read-only. Can anyone lend a hand? Whenever I try to send a Post Request, my editor just won't cooperate and stays in Read-Only mode. ...

JavaScript seems to have difficulty correctly parsing objects from JSON

Having trouble populating a Repeat Box with objects from a JSON document. Despite my efforts, it keeps duplicating the first item instead of adding each one individually. Any ideas on what might be causing this issue? Below is the code I am currently usin ...

What is the best way to streamline a state-dependent getter, with a focus on adhering to SOLID principles?

Is there a more user-friendly way to retrieve different data based on the type in my Angular component? I'm considering separating the component into two: one for phone and one for email. However, I'm concerned about duplicating most of the logi ...

Can the Angular link function activate the change event?

I am facing an issue with my Angular directive that includes a link function. Inside this function, I am initializing a jQuery plugin which can be seen in action here: https://plnkr.co/edit/58nOhypt6FRdI4At5jwu. The problem arises when every time the dire ...

Creating an Injectable AppSettings Class in Angular 2

Currently, I am working with Angular 2 within an ASP.NET Core application, although the specifics of that setup are not crucial to my current issue. My main task at hand involves fetching configuration values from the server and integrating them into my An ...

The ajaxStart event does not seem to be triggering when clicked on

I am having trouble adding a loader to my site using the ajaxStart and ajaxStop requests to show and hide a div. The issue is that these requests are not being triggered by button onclick events. <style> // CSS for loader // Another class with o ...