Most effective method to change a specific attribute in every element within a nested array of objects

Below is an example of my data object structure:

const courses = [
    {
        degree: 'bsc',
        text: 'Some text',
        id: 'D001',
    }, 
    {
        degree: 'beng',
        text: 'Some text',
        id: 'D002',
    },  
    {
        degree: 'bcom',
        text: 'Some text',
        id: 'D003',
        electives: [
            {
                degree: 'bsc',
                course: 'Psychology'
                text: 'Some text',
                id: 'C010',
            },
        ],
    },
];

I want to update the text property in all objects, including those nested in arrays. The desired format looks like this:

const courses = [
    {
        degree: 'bsc',
        text: translateText('D001'),
        id: 'D001',
    }, 
    {
        degree: 'beng',
        text: translateText('D002'),
        id: 'D002',
    },  
    {
        degree: 'bcom',
        text: translateText('D003'),
        id: 'D003',
        electives: [
            {
                degree: 'bsc',
                course: 'Psychology'
                text: translateText('C010'),
                id: 'C010',
            },
        ],
    },
];

I aim to achieve this transformation by passing the Id property as a parameter. Below is my current method:

courses.forEach(course => {
    course.text = translateText(course.id);
    if (course.degree === 'bcom') {
        course.electives.forEach(elective => {
            elective.text = translateText(elective.id);
        })
    }
});

I am not entirely satisfied with this approach as it could become cluttered if more arrays are added to different degree types. Additionally, I am concerned about potential performance implications. Is there a cleaner and better way to accomplish this?

Answer №1

@Nenad was first to mention the recursive function, but I still wanted to share my answer because it offers a way to recurse through any nested objects, not just the electives property. Take a look at this approach:

const courses = [
    {
        degree: 'bsc',
        text: 'Some text',
        id: 'D001',
    }, 
    {
        degree: 'beng',
        text: 'Some text',
        id: 'D002',
    },  
    {
        degree: 'bcom',
        text: 'Some text',
        id: 'D003',
        electives: [
            {
                degree: 'bsc',
                course: 'Psychology'
                text: 'Some text',
                id: 'C010',
            },
        ],
    },
];

const translateTextProperty = function(obj) {
  if( typeof obj.text != 'undefined' )
    obj.text = translateText(obj.id);
  
  for(let key in obj ) {
    if( obj[key] instanceof Object ) {
      translateTextProperty( obj[key] );
    }
  }
}

courses.forEach( c => translateTextProperty(c) );

Answer №2

A recursive function can be utilized to search for the electives key within an object and update the nested data structure if it exists.

const courses = [{"degree":"bsc","text":"Some text","id":"D001"},{"degree":"beng","text":"Some text","id":"D002"},{"degree":"bcom","text":"Some text","id":"D003","electives":[{"degree":"bsc","course":"Psychology","text":"Some text","id":"C010"}]}]

const f = text => text + ' - updated';
const update = data => {
  data.forEach(e => {
    if (e.text) {
      e.text = f(e.text)
    }

    if (e.electives) {
      update(e.electives)
    }
  })
}

update(courses);
console.log(courses)

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

Prevent background music from being manipulated

I've implemented an audio HTML element with background music for a game: <audio class="music" src="..." loop></audio> However, I have encountered an issue where upon loading the page, I am able to control the music usi ...

Generate a NumPy array by assigning names from a given list

I am struggling to create multiple NumPy arrays based on a list of names. For instance, I have the following list: k=["one","two","three"] I want to generate three arrays with names corresponding to each element in the list. This means: one=np.array() t ...

Retrieve the IDs of list elements in order to dynamically update a div using AJAX

I'm facing a bit of a challenge at the moment. I have a webpage that uses jQuery to load three different views: one displaying all categories associated with the user, another showing the image and name of items within the selected category, and a thi ...

Having trouble choosing the component-button using Protractor

I'm having trouble selecting the "Add New" button using any locator component. Check out the audience.po.ts file and the method "ClickAddNewBtn()": clickAddNewBtn() { console.log("Clicking on the Add New button."); return element(by.cs ...

Pass JavaScript variables to a PHP file with the help of AJAX

Hey there, I'm new to developing web-based applications and currently learning about AJAX. I've run into a problem while trying to make an AJAX request with user inputs as variables and fetching the same variables in a PHP file. Below is the code ...

Using CSS height 100% does not function properly when the content overflows

Here's what's going on with this code snippet: HTML <div class="one"> <div class="will-overflow"> </div> </div> CSS html, body { width: 100%; height: 100%; } .one { height: 100%; background: r ...

Sending form data from a third-party website to Django

Currently, I am running a Django website that holds user information. My goal is to host forms on external websites, such as a newsletter signup form. I want to be able to extract data from a queryset in the URL and send it back to my Django site. At the m ...

Is it beneficial to rotate an image before presenting it?

I am looking for a way to display a landscape image in portrait orientation within a 2-panel view without altering the original file. The challenge I am facing is that the image size is set before rotation, causing spacing issues with DOM elements. Is ther ...

How to update JSON file on server using JavaScript

I am encountering an issue that has been discussed quite frequently. Despite trying various solutions, none have proven effective so far. The problem lies in my JavaScript file where I have some data that I need to append to an existing .json file on my s ...

Are you curious about the array of elements in React's carousel?

I'm currently in the process of constructing a website using React, and I have a specific challenge related to the "news" section. Within this section, I have a list of three components that represent different news items. These components are housed ...

When using Sequelize, I encountered an error message from SQLite stating that the table does not exist despite having created

I am struggling to grasp the concept of how Sequelize operates and I can't figure out why I am encountering the SQLITE_ERROR: no such table: Users error even though I have created the table using sequelize.define. Here is my code: const { Sequelize, D ...

Retrieving information and employing the state hook

Currently, my goal is to retrieve information from an API and utilize that data as state using the useState hook. fetch('https://blockchain.info/ticker') // Execute the fetch function by providing the API URL .then((resp) => resp.json()) // ...

Execute protractor to open chrome in incognito mode and disable web security for cross-origin resource sharing

Our application performs well in production with CORS enabled. I am working on a project that is not CORS-enabled locally. Is there a way to disable web security for protractor? Can I modify the selenium instance by adding arguments? We are interested in ...

Is there a way to dynamically modify the email content with the Gmail API using JavaScript?

I have received the message body and now I need to make some updates to it. When I try using this login/code, I encounter a 400 error. I believe the issue lies in the body parameter of the request. Can someone please assist me with this? var token = loca ...

Effortlessly showcase JSON data in an HTML owl carousel

Is there a way to display JSON data in HTML format? I have a JSON file containing reviews from Facebook, and I would like to showcase them on my website. Each review should be placed in its own div element. The JSON data below is extracted from the Faceboo ...

Understanding the process of accessing data within the beforeRouteLeave component guard in Vue

Having trouble accessing data within beforeRouteLeave as everything appears to be undefined Check out the code snippet below: <template> ... </template> <style lang="scss"> ... </style> <script> export default { ...

Display Error with Custom Alert Box

I recently implemented a customized alert box from slayeroffice's website, which you can find at slayeroffice.com/code/custom_alert/. When I view it on my browser, the alert box appears with a blue color in the center of the screen. Here is how it lo ...

Enhance user experience with PrimeFaces by implementing an Ajax update feature through

I'm interested in using PrimeFaces to ajax update a JavaScript script. <script type="text/javascript"> <!-- function lineChartExtender(){ this.cfg.highlighter = { showTooltip: true, tooltipAxes: &apos ...

Learn how to creatively style buttons with dynamic effects using tailwindcss

My Desired Button: I have a Button component that can accept a variant prop. My goal is to have the button's className change dynamically based on the prop passed to it. Instead of using if/else statements for different buttons, I want to use a sing ...