Optimal approach for incorporating individual identifiers into a complex hierarchy of object arrays

I am looking to assign unique ids to an array of objects: For example:

const exercises = [
  { 
    type: "yoga",
    locations: [
      {
        name: 'studio',
        day: 'Wednesday'
      },
      {
        name: 'home',
        day: 'Friday'
      }
    ],
    active: true
  },
  { 
    type: "swim",
    locations: [
      {
        name: 'pool',
        day: 'Tuesday'
      },
      {
        name: 'lake',
        day: 'Thursday'
      }
    ],
    active: true
  }
]

In this scenario, I aim to add ids to the exercises array and its nested locations array. My approach involves iterating through the arrays as shown below:

const idMappings = exercises.map((exercise) => {
    const exerciseIdMapping = exercise.id ? exercise : { ...exercise, id: uuid.v4() }; // if id exists, return object as is; else generate a random id
    const locationsIdMapping = exerciseIdMapping.locations.map((location) => {
        return location.id ? location : { ...location, id: uuid.v4() }; // repeat process for nested array
    });
    return { ...exerciseIdMapping, locations: locationsIdMapping }; // return updated values with ids
});

The result includes unique ids for each location:

const exercises = [
  { 
    id: "0000-0000-8888-9f24-f8e1f2402a9b",
    type: "yoga",
    locations: [
      {
        id: "0000-1111-7777-9f24-f8e1f2402a9b",
        name: 'studio',
        day: 'Wednesday'
      },
      {
        id: "0000-2222-6666-9f24-f8e1f2402a9b",
        name: 'home',
        day: 'Friday'
      }
    ],
    active: true
  },
  { 
    id: "1111-0000-4444-9f24-f8e1f2402a9b",
    type: "swim",
    locations: [
      {
        id: "1111-1111-3333-9f24-f8e1f2402a9b",
        name: 'pool',
        day: 'Tuesday'
      },
      {
        id: "1111-2222-2222-9f24-f8e1f2402a9b",
        name: 'lake',
        day: 'Thursday'
      }
    ],
    active: true
  }
]

While this method achieves the desired outcome, I wonder if there is a more efficient way to tackle this issue. Are there alternative ES6 functions that could streamline this process without multiple mappings?

Answer №1

Perhaps utilizing recursion would be beneficial in this scenario. Consider implementing it as shown below:

function assignUniqueIds (arr) {
  arr.forEach(item => {
    item.id = uuid.v4()
    if (item.subsections && item.subsections.length > 0) {
      assignUniqueIds(item.subsections)
    }
  })
}

assignUniqueIds(contentSections)

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

How to use OBJLoader/Three.js to load a specific URL in JavaScript

I am encountering an issue with a JavaScript code snippet from the three.js OBJloader. I should mention that my experience level in JS and PHP is limited as I am just starting out with WordPress websites. My problem lies in utilizing the setPath and load ...

Are there any methods for updating redux-form's submitting property with a workaround?

I have integrated reCAPTCHA v2 with a sign-up form that is using redux-form. The issue I am facing is that when the user submits the form, the reCAPTCHA modal pops up and the redux-form's 'submitting' prop changes from 'false' to & ...

Store the incoming documents from xmpp using the Strophe si-filetransfer feature

I am currently working on adding file transfer functionality to my web application using the strophe.si-filetransfer.js plugin. I have successfully received file details within an iq stanza. My inquiry is, how can I extract the file data from this iq stanz ...

What is the proper way to add a string to a TypeScript array?

When attempting to add a string to a TypeScript array, I am encountering an error stating 'cannot push to undefined'. Is this the correct approach, or should I be using the spread operator instead? api.ts const api: IConfigName = {name: "getKey ...

The react-xml-parser package is asking for Babel version "^7.0.0-0", however it was instead loaded with version "6.26.3". I have already attempted all available solutions to resolve this issue

I have attempted numerous solutions from the Github community regarding this issue, but unfortunately none have worked for me. /node_modules/react-xml-parser/dist/bundle.js: Requires Babel "^7.0.0-0", but was loaded with "6.26.3". If you are sure you ha ...

Hide the search results if the user leaves the input field blank

I am trying to implement Live Search JSON Data Using Ajax jQuery, and I want to be able to search through multiple JSON files. When the page initially loads with an empty input field, no results are displayed. However, if you type and then delete text in ...

Change the blue line to a crisp, clean white

Is it possible to customize the color of the blue line that appears when clicked? class Greetings extends React.Component { render() { return <div>Greetings {this.props.name}</div>; } } ReactDOM.render( <div> <p tabInde ...

Align the image in the middle using JavaScript for Firebase

I am struggling to display the center of an image within a circle-shaped <img> tag with a border-radius of 50%. The issue arises when trying to display an image fetched from Firebase storage, rather than from a URL. In attempt to solve this problem, ...

Receiving multiple Firebase notifications on the web when the same application is open in multiple tabs

I have implemented firebase push notifications in Angular 7 using @angular/fire. However, I am facing an issue where I receive the same notification multiple times when my application is open in multiple tabs. receiveMessage() { this.angularFireMess ...

Utilizing cloud functions to distort an inappropriate image

I have a requirement to analyze any uploaded image for inappropriate content and blur it if necessary. The log this image is inappropriate indicates that the detection process is working correctly. However, I am not able to see any further logs which sugg ...

A grid displaying relationships between elements, with both the vertical and horizontal axes labeled using

To establish an Adjacency matrix with rows and columns represented by Strings and containing either 0 or 1 to indicate a connection between the source and destination nodes. For instance, if a connection exists from a to b and b to c, the matrix would loo ...

Codeigniter dropdown sending incorrect value to controller

When I choose an option from the dropdown list and click the submit button in the modal, the selected value is not being posted to the controller as expected. Below is my view code: <div class="form-group"> <div class="col-md-4"> ...

The HttpParams are reluctant to be established

Working with Angular 8, I am attempting to assign an HttpParam using the provided code snippet and observing the outcome on the final line. let newParams = new HttpParams(); newParams.set('ordering', 'name'); console.log('getting: ...

Tips for utilizing AJAX to send data from a specific row

<table> <tr data-id="1"> <input type="text" name="name_1" value="abc"> <input type="text" name="value_1" value="1"> <a href="load_edit_row(this)">Edit</a> </tr> <tr data-id="2"> <input t ...

Getting the most out of the fastest-validator package: Implementing multiple patterns and custom messages

Utilizing the powerful fastest-validator library for validation purposes. I have a requirement where the password field must contain at least one character and one number. Along with this, I am in need of specific messages for validating these conditions ...

Retrieve the unique payment ID generated from the database and present it on the frontend

Greetings, I am currently working on integrating a payment processor and I require the automated generation of the corresponding payment ID in the backend. On the frontend side, I have implemented JS to request data from the backend, but I'm facing ...

How can a jQuery fadeTo Effect be timed?

Presently, I am utilizing jQuery's fadeTo function to gradually fade in a div. Nevertheless, I am encountering a slight timing issue. I have an Animated GIF file that I wish to synchronize with the jQuery fadeTo effect. I have tried using window.onlo ...

Cannot instantiate Marker Clusterer as a constructor

I am facing an issue with implementing Marker Clusterer in my app. I have successfully installed '@google/markerclusterer' in my project and imported it as shown below. However, a puzzling error keeps popping up: core.js:4002 ERROR TypeError: _go ...

Ban on the utilization of emojireact-role in external channels

How can I ensure that the bell reaction only gives a role in a specific channel? The provided code is below. Additionally, is there a way to restrict this feature so only administrators can assign roles through reacting with a bell emoji? Any assistance ...

URL-based authentication using Passport.js

I am currently working on my app using Express JS and Passport JS. My goal is to allow a new user to automatically log in once by accessing a specific URL. I have the ability to retrieve the user information from the database based on the URL provided, re ...