Evaluate each object in the array and modify its attributes

When I receive arrays of objects structured like this, my goal is to iterate through them and concatenate a variable in order to create the following links:

link: `${id}/users`
link: `${id}/add-user`

...

id= school1;

dashboardMenu = [
    {
      title: "Dashboard",
      icon: "home-outline",
      link: "/",
      home: true,
      children: undefined,
    },
    {
      title: "Users",
      icon: "person-outline",
      link: "/users",
      data: "read:users",
      children: [
        {
          title: "Users",
          link: "/users",
          data: "read:users",
        },
        {
          title: "Create User",
          link: "/add-user",
          data: "create:users",
        },
      ],
    }
 ]

Answer №1

One potential solution could be to iterate through the object and its nested elements, adding a specified id to each link. Here's an example of how you could implement this:

let id = "school1";
let dashboardMenu = [
  {
    title: "Dashboard",
    icon: "home-outline",
    link: "/",
    home: true,
    children: undefined,
  },
  {
    title: "Users",
    icon: "person-outline",
    link: "/users",
    data: "read:users",
    children: [
      {
        title: "Users",
        link: "/users",
        data: "read:users",
      },
      {
        title: "Create User",
        link: "/add-user",
        data: "create:users",
      },
    ],
  },
];

let result = dashboardMenu.map((o) => {
  o.link = id + o.link;
  if (o.children) {
    o.children.forEach((child) => (child.link = id + child.link));
  }
  return o;
});

console.log(result);

To apply this recursively, you could try a function like the following:

let dashboardMenu = [{
    title: "Dashboard",
    icon: "home-outline",
    link: "/",
    home: true,
    children: undefined,
  },
  {
    title: "Users",
    icon: "person-outline",
    link: "/users",
    data: "read:users",
    children: [{
        title: "Users",
        link: "/users",
        data: "read:users",
      },
      {
        title: "Create User",
        link: "/add-user",
        data: "create:users",
      },
    ],
  },
];

setNestedLink = (o, k, id) => {
  if (o[k]) {
    o[k] = id + o[k];
    if (o.children) {
      o.children.forEach((child) => setNestedLink(child, k, id));
    }
  }
  return o;
};


let result = dashboardMenu.map((o) => setNestedLink(o, "link", "school1"));

console.log(result);

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

Sending response error codes in nodejs can be achieved using a variety of methods

I am looking for a way to properly send an error code as a response in a promise within a Node.js application. It seems that errors in promises are not being sent correctly in the response object in NodeJS/Express. module.exports.providerData = function ( ...

Is requestAnimationFrame not supported in iOS UIWebView?

Is there a replacement for requestAnimationFrame that works in UIWebView, since it seems to be undefined? Or will I need to resort to using setTimeout instead? ...

Learning how to handle URLEncoded format in Vue JS

Seeking guidance on how to handle URL Encoded format in postman to send data to my Vue JS app. Using the encoded format shown below, what npm package should I utilize for this task? https://i.stack.imgur.com/sBkXi.png ...

How is it possible for a function set to execute on click to be triggered on page load instead?

I'm new to posting on stackOverflow, and I really hope I don't mess it up. Currently working on a website using Compass, Foundation, and jQuery but encountering an issue with my code: $(document).ready(function(){ function navOn(){ ...

The <b-list-group-item> component in a Vue.js CLI application using bootstrap-vue is failing to render

My Vue-CLI app uses Bootstrap-vue and axios to fetch JSON data. The HTML code in my App.vue displays the data using UL and LI tags: <p v-if="loading">Loading...</p> <ul v-else> <li v-for="(value, key) in post" :key="key"> ...

Overcoming Time Limits: What are the best strategies for maximizing performance in my JavaScript code?

I am currently tackling the challenge of solving the Sum of Subarray Ranges problem on LeetCode. Unfortunately, I am encountering a Time Limit Exceeded error which suggests that my code might not be optimized efficiently enough. As I am still learning, I w ...

Use a for loop in html, css, and javascript to generate unique element ids with corresponding values

Can you assist me in creating a function to generate element_id-value pairs and saving them into a file with the use of a for loop? <body> <form class="box1" > <fieldset> <label class="my_text4" >firstelement&l ...

sophisticated HTML navigation bar

I am looking for a way to create a menu where the drop-down items overlay the rest of the menu when the screen width is small. Here is my current code: nav{ line-height:100%; opacity:.9; }nav ul{ background: #999; padding: 0px; border-radius: 20px; ...

What is the best way to incorporate an asp helper within a javascript script?

I am working on a JavaScript page layout and trying to incorporate CMS helpers into it. Despite successful rendering, the helpers are not functioning as expected (resulting in "NaN" instead of the desired text). How can I integrate helpers into a JavaScr ...

String parameter with a variable

I'm currently tackling a challenge with my table constructor in one of my more extensive projects. The issue I am facing is that the variables in the content I am trying to pass on to the constructor function are getting evaluated before they are actu ...

Generate a random number using the Math.random() method in Node.js/JavaScript to access a folder on the local machine

I am facing a challenge in reading a JSON file located deep within multiple folders on my local machine. The issue arises because the folder name where the file is stored changes every time, as it is generated using the Math.random() method with the prefix ...

Vue-ctl project creation halted by operating system rejection

While working on a Vue-CLI project, I encountered an issue. Has anyone else faced this problem before? Operating system: Windows 10 - Command Prompt (admin rights) @vue-cli version: 4.5.4 npm version: 6.14.6 Here is the command I ran: vue create font_ ...

By default, configure the MUI Collapse component to be in a "collapsed" state

I'm currently working on a React/Next/MUI project and I have a query regarding the default setting for the MUI Collapse element. I would like it to be collapsed by default instead of being opened, especially when dealing with large navigations. Here&a ...

Having trouble retrieving JSON data from the controller while utilizing Angular's $http method

Trying to extract information from an action in my controller. The current state of the action is as follows: def index @users = User.all respond_to do |format| format.html format.json { render json: @users } ...

Creating elements in Polymer 2.0 is a breeze. Simply use the `createElement` method, then seamlessly import it using `Polymer

While working on a project, I encountered an issue where I was creating and importing an element while setting attributes with data. The code should only execute if the element hasn't been imported or created previously. However, each time I called th ...

Issue with Jquery code on Mac OS Chrome - it's functional on Windows 10 Chrome though!

Upon clicking the image, it should hide and the YouTube video plays automatically. This functionality works perfectly on Windows 10 but is not functioning on Mac OS or iOS. I am seeking assistance in resolving this issue. I do not own a MacBook, but my c ...

Tips on managing JavaScript pop-up windows with Selenium and Java

There have been numerous solutions provided on Stack Overflow for handling JavaScript windows, but my situation is quite unique. I am currently working on automating a process for our web-based application. The development team recently implemented a MODA ...

Effective ways to retrieve API response data in React JS

I am working on a Spring Boot project which includes an API for user login. When the user name and password are sent through this API, it checks the database for the information. If the data is found, it returns a successful login message; otherwise, it ...

Maximizing Efficiency with Single Click Line Editing in the Newest Version of jqgrid

There seems to be an issue with single click inline row editing in the latest free jqgrid from github master. BeforeSelectRow, clicking on a row to start inline editing causes an exception: Uncaught TypeError: Cannot read property 'rows' of unde ...

How can I add color to arrow icons in tabulator group rows?

Is there a way to specify the color of the arrows in collapsed/expanded group rows? Also, what CSS code should I use to define the font color for column group summaries? You can view an example of what I am trying to customize here: https://jsfiddle.net/s ...