Tips for changing an array of objects with identical key names?

Here's an array of objects:

p =[
{
    "object1": "value",
},
{
    "object2": "value",
},
{
    "object1": "value",
},
{
    "object3": "value",
},
{
    "object4": "value",
},
{
    "object1": "value",
},
{
    "object3": "value"
}
];

I'm looking to adjust the keys of objects that share the same key. Any thoughts on how I can achieve this?

The desired output should be:

p =[
{
    "object1_1": "value",
},
{
    "object2": "value",
},
{
    "object1_2": "value",
},
{
    "object3_1": "value",
},
{
    "object4": "value",
},
{
    "object1_3": "value",
},
{
    "object3_2": "value",
}
];

The goal is to maintain the structure of the array as much as possible, with the only changes being updates to duplicate keys.

Answer №1

To determine the frequency of each key value, you can create a new object to keep track of how many times each key appears.

var tracker = {};

var updatedArray = originalArray.map(function(item){
    var key = Object.keys(item)[0];

    tracker[key] = (tracker[key] || 0) + 1;

    var name = key + '_' + tracker[key];
    
    var newObj = {};
    newObj[name] = item[key]; 
    return newObj;
});

NOTE:

It's advisable not to use "set" as the variable name. Also, consider removing the '_1' for the first occurrence by checking if statement like this:

var finalName;
if (tracker[key] === 1 ) { 
   finalName = key;
} else {
   finalName = key + '_' + tracker[key];
}

If you only want to add '_1' to repeating elements, you could iterate through the array once more using the final counts.

Answer №2

To tackle this problem, you will need to loop through the array twice. First, identify the keys that are repeated, and then replace their corresponding values in a second iteration.

var arr = [{
  "key1": "value",
}, {
  "key2": "value",
}, {
  "key1": "value",
}, {
  "key3": "value",
}, {
  "key4": "value",
}, {
  "key1": "value",
}, {
  "key3": "value",
}];

var keyCount = {};
var valueIndex = {};

function processKeys(callback) {
  for (var i = 0; i < arr.length; i++) {
    var obj = arr[i];
    var key = Object.keys(obj)[0];
    var countForKey = keyCount[key];
    callback(obj, key, countForKey);
  }
}

processKeys(function(obj, key, countForKey) {
  keyCount[key] = countForKey ? countForKey + 1 : 1;
  valueIndex[key] = 0;
});

processKeys(function(obj, key, countForKey) {
  if (countForKey !== 1) {
    var idx = valueIndex[key] + 1;
    valueIndex[key] = idx;
    obj[key + "_" + idx] = obj[key];
    delete obj[key];
  }
});

console.log(arr);

Execute the code snippet and review the console output for the updated 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

PHP MySQL query with Associative Arrays

Trying to execute a mysql query in php: mysqli_query($link,"SELECT * FROM `content` WHERE `page`='$cont_sel_e['name']'") Unfortunately, the query is not returning any results. I suspect the issue lies with the single quotes in the &ap ...

Utilizing Angular PrimeNG's range datepicker, you can select a date range spanning from January 31st to December 1st, 2023 within a reactive form. Take it a step further by calculating

Here is some HTML code: <div class="row"> <div class="col-4"> <p-calendar label="startDate" formControlName="startDate" [minDate]="daMaxRange" ...

Determine the sphere's color using the coordinate system in three.js

Is there a way to customize the color of this sphere rendered in three.js based on its coordinates? For instance, can I make the top half of the sphere red and the bottom half black? var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamer ...

Error: Angular ng-file-upload successfully uploads file, but Node.js fails to receive it

Currently, I am working on loading and cropping a file using Angular. Many thanks to https://github.com/danialfarid/ng-file-upload SignUp2ControllerTest -- $scope.upload --> data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAg ...

Emerald: Fresh alert for numerous attributes

After updating jade to the latest version, I started seeing a message in the console that says: You should not have jade tags with multiple attributes This change was mentioned as a feature here 0.33.0 / 2013-07-12 Hugely more powerful error reporting ...

Communicating an array of structures with a pointer through MPI

I am dealing with a C structure that looks like this: typedef struct chromosome{ int *genes; float cout; }chromosome; My goal is to transmit a collection of chromosomes using MPI_Send. I've defined an MPI_CHROMOSOME data type in the following way: ...

Using JavaScript and jQuery to toggle visibility of a dynamically created input field

This script dynamically generates a group of elements consisting of four input fields. Once an element is created, you can select or deselect it, which will trigger the corresponding editor to appear. I have implemented a function to specifically hide the ...

Calculate the number of arrays in an object and then substitute them

Currently, I have an object that is returning the following data: Object {1: 0, 2: Array[2], 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0} My goal is to replace the "Array[2]" with just the number "2" (indicating how many records are in ...

The append() function works only the first time when the same code is being appended to the same div

$('.addvalue').change(function(){ val_id = this.id; count_new_btn++; count_new_inp++; if( $('#'+val_id).val() == '1'){ $('#div'+ val_id).append('<input ...

Vue 3 and Bootstrap 5 seem to be struggling with finding the properties of an undefined 'backdrop'

I am facing an issue with Vue3 (Vite) and Bootstrap 5 while trying to create a modal that can be called by code. The problem arises when I attempt to open the modal from its parent component. Bootstrap has been properly installed and included in my projec ...

Assigning information to a button within a cell from a dynamically generated row in a table

I've been diligently searching through numerous code samples but have yet to find a solution to my current dilemma: My HTML table is dynamically generated based on mustache values and follows this structure: <tbody> {{#Resul ...

How to dynamically disable options in a Vuetify v-select based on the type of object value

When utilizing the Vuetify v-select component and setting the prop multiple, we can select multiple values at once. In this scenario, I have a variety of recipes categorized under Breakfast or Dinner using the parameter type. The goal is to deactivate al ...

Is it considered a best practice to use collection.find() to retrieve all items on a master node in Mongo?

Every night at midnight, a background process retrieves all users from MongoDB and performs various checks and processes on their accounts. I have some questions regarding this process: Is it efficient in terms of performance to use the following query t ...

Encountered an error trying to access property 'history' of an undefined value while using react-router v4 and create-react-app

I encountered an issue with using Link to navigate, here's the breakdown of my code: Directory structure components ----App.js ----home ----Home index.js index.js import React from 'react'; import ReactDOM from 'react-dom'; ...

Strategies for organizing and handling npm packages within my codebase

Recently, I decided to create a discord bot and used npm for the first time. After setting up my package file and installing discord.js, I now find myself with 3000 files that could be synced to my repository. It seems like an overwhelming situation, and I ...

Issue encountered while attempting to transfer data via the $.ajax method

I created a poll form using radio buttons. To submit the form, I utilized $.ajax. However, when I tried using $("#polling").serialize() to gather the data, nothing was sent or requested... Could the issue be related to the radio buttons? $(function( ...

Parse a string in the format of "1-10" to extract the numbers and generate an array containing the sequence of numbers within the range

Looking to convert a string in the format "1-10" into an array containing the numbers within that range. Display the array on the screen using a for loop. For example, if "1-5" is provided, the resulting array should be: {1, 2, 3, 4, 5} Create a workflow ...

What are some ways to ensure that a webpage has been actively viewed for a minimum of X seconds?

In my project, users have the opportunity to earn a bonus by viewing specific pages. When they visit the bonus selection site, an iframe displays the page along with a countdown timer. Once the countdown reaches zero, they can then click the "Get Reward" b ...

Accessing values from a JSON object in AngularJS without using a loop based on another field

Is there a way to extract the "value" associated with the "name" in JSON using Angular JS without having to iterate through the array? For instance, if I have an array like the one below with name and value fields, how can I retrieve the value "ABC" based ...

Using touch-action to enable movement from the last item to the first item in HTML/C

Currently, I am utilizing the touch-action property in my carousel which auto slides without any issues. However, I am facing a problem where when I scroll using touch-action, it stops at the last slide instead of looping back to the first slide. My goal i ...