Ways to change an array of objects with similar named values

Here is an array of nested objects:

    var existingArray = [{
            "content": {
                "host": {
                    "name": "Mia"
                }
            },
        }, {
            "content": {
                "host": {
                    "name": "Annie"
                }
            },
        }, {
            "content": {
                "host": {
                    "name": "Mia"
                }
            },
            ,
            {
                content: {
                    host: {
                        name: "Oscar"
                    }
                },
            },
            {
                "content": {
                    "host": {
                        "name": "Annie"
                    }
                },
            },
            {
                "content": {
                    "host": {
                        "name": "Mia"
                    }
                },
            },
            {
                "content": {
                    "host": {
                        "name": "Annie"
                    }
                },
            }
        ];

If I need to modify the object's name value when they match, how would I do it?

To create a new array like this:

        var existingArray = [{
            "content": {
                "host": {
                    "name": "Mia"
                }
            },
        }, {
            "content": {
                "host": {
                    "name": "Annie"
                }
            },
        }, {
            "content": {
                "host": {
                    "name": "Mia_2"
                }
            },
            ,
            {
                content: {
                    host: {
                        name: "Oscar"
                    }
                },
            },
            {
                "content": {
                    "host": {
                        "name": "Annie_2"
                    }
                },
            },
            {
                "content": {
                    "host": {
                        "name": "Mia_3"
                    }
                },
            },
            {
                "content": {
                    "host": {
                        "name": "Annie_3"
                    }
                },
            }
        ];

The goal is to maintain the array structure almost the same, with only changes made to duplicate name values.

This adjustment is necessary because a plugin I am using identifies and merges duplicate names (the details are too complex to explain here).

Answer №1

Here is a possible solution that may meet your needs:

let i;
let j;
for(i = 0; i < currentList.length; i++){
    let count = 2;
    for(j = 0; j < currentList.length; j ++){
        if(i != j && currentList[i].content.name === currentList[j].content.name){
            currentList[j].content.name += '_' + count;
            count++;
        }
    }
}

Answer №2

Keep a record of each unique name used along with the frequency of its usage.

Then, during each iteration, check if the name has been used before by referring to this record.

If the name is new, add it to the list and set its count to 1. The original name will be retained in this scenario.

If the name is not new, increment its count in the list. In this case, the updated name will include an underscore followed by its count.

var existingArray = [  
   {  
      "content":{  
         "host":{  
            "name":"Mia"
         }
      }
   },
   {  
      "content":{  
         "host":{  
            "name":"Annie"
         }
      }
   },
   // Additional array items excluded for brevity
]
,   usedNames = {}
,   newArray = []
,   result = ''
;
for(var index = 0; index < existingArray.length; index ++) {
    var name = existingArray[index]['content']['host']['name'];
    newArray.push(existingArray[index]);
    if(typeof usedNames[name] !== 'number') {
        usedNames[name] = 1;
        newArray[index]['content']['host']['name'] = name;
    } else {
        usedNames[name] ++;
        newArray[index]['content']['host']['name'] = name + '_' + usedNames[name];
    }
    result += 'content: host: name: ' + newArray[index]['content']['host']['name'] + '<br/>';
}
document.write(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

The length of JSONPath in Javascript is significantly longer, approximately 3000 times lengthier than a traditional loop

I am experiencing performance issues with JSONPath implemented in JavaScript using the Stephan Goessner Library. Below is an example of the JSON structure causing the problem: [ { id:1, name: "lorem", elements: [ ...

Slick Slideshow: Deleting the Present Slide

Can anyone help me figure out how to remove the current active slide using Slick.js? I've tried multiple ways but nothing seems to work. var $status = $('.pagingInfo'); var $slickElement = $('.slideshow'); $slickElement.on(' ...

What is the best way to iterate through shared fieldsets within a single form using PHP?

I am encountering a situation where I have a form with multiple virtual fieldsets. For example, consider my form structure: Name1 Age1 Location1 Name2 Age2 Location2 Name3 Age3 Location3 Submit If I give users the ability to dynamically add more fie ...

Tips for inserting user input into an array and showcasing it

const [inputValue, setInputValue] = useState(""); return ( <input onChange={(event) => setInputValue(event.target.value)} /> <p>{inputValue}</p> ); I'm facing a problem where I need to take input from a user and store it in ...

What steps should I follow to incorporate this filter into my code?

Currently, I am working with a list of names obtained from an array using the Fetch method. I have implemented a searchHandler method which is triggered by a button click, and it logs the input data in the console: https://codesandbox.io/s/jovial-lovelac ...

Discover the key technique to modify the status of a different component in React

I'm working on developing a popup window component. Here is the initial code for the popup component: The component takes in two props, activity (which can be set to true or false) and content (a view component that will be displayed inside the popu ...

Difficulties arise when trying to pass all data inputted on a form using formData in conjunction with the fetch API

Why is my formData appearing empty when sent to my express+mongodb server? I'm having some issues with querySelector and addEventListener, but for now that's manageable. However, I am struggling to find a way to successfully send all the values o ...

Identical characteristics on display in $mdToast

I have created a custom function to display multiple toasts at the same time, but only the last action has the passed values while other values remain as the first toast. Check out the screenshothttps://i.sstatic.net/IuQYw.png Here is my code snippet ...

Retrieve the following object in an array of objects using a specific property value in Javascript

I am working with an array of objects structured like this: orders: [ 0: { order_id: 234, text: 'foo' }, 1: { order_id: 567, text: 'bar' } ] Suppose I have the ID 234 and I want to find the next object in the a ...

Checking for an existing alert in JavaScript

In my development of a Blackberry Webworks (HTML5) app, I am running multiple methods simultaneously in the background. If any of these methods happen to fail, an alert is triggered using the alert() method in JavaScript. However, if both methods fail, two ...

Storing pixel data in a text file

I am currently working with an array of pixel values extracted from a greyscale image. My goal is to export these values either into a text file or CSV format. I have experimented with several functions, including xlsxwrite, write, and CSV, but have not ye ...

Can a Javascript binary search only match on values greater or equal?

When searching, this code will find the closest match. Usually, the closest match's x value is smaller than the target.x. Is there a way to find the closest match where match.x is greater than or equal to the target.x value and match.y is the nearest ...

What is the best way to save the values of all the input fields in a datatable, excluding any fields that are empty?

$('form').on('submit', function(e){ var form = this; // Encoding a set of form elements from all pages as an array of names and values var params = table.$('input').serializeArray(); // Iterating over all form ...

Angular file upload component with customizable file size limits

I'm currently developing an upload file feature that will transmit the file via nodejs. However, I am encountering an issue related to file size. Whenever the file exceeds a few kilobytes, I encounter the following error: Error: request entity too la ...

Easily integrate an HTML form as an input for your Python script

Despite my thorough searches, I haven't been able to find a satisfactory answer. I am creating a local HTML page with Python and would like to extract data from a form on that page, use it as input for a Python script, and then properly display the r ...

Popup showing values that are not defined

I've encountered an issue with tooltips on my bar graph. The tooltips should display the values of boarding and alightings corresponding to each stopname column, but I'm seeing undefined values like this Below is my code snippet: <!DOCTY ...

What is the best method for selecting the parent using jQuery?

How can I dynamically add a "selected" class to the parent item if any of its children have a "selected" class in my recursive menu setup shown below? <ul> <li class="administration first"> <a href="/administration.aspx">&l ...

What could be causing the delay in this script's execution?

I'm attempting to include a script at the beginning of my XBL file, however even the test below is not functioning. Any insight on why this might be happening? <bindings xmlns="http://www.mozilla.org/xbl" xmlns:xbl="http://www.mozilla.org/x ...

JavaScript Regex: Removing all characters that are not numbers

There have been several inquiries about this particular question, such as this one on Stack Overflow. Despite my efforts to replicate the solution and research regex, I can't seem to get it to work: $("#button").click(function () { new_number = $ ...

Retrieve information from various tables in a SQLite database using Node.js

Is there a method to retrieve all data from multiple tables in a database? Currently, I have managed to fetch all data from a single table: router.get('/', function (req, res, next) { db.serialize(function () { db.all('SELECT id, name ...