Adding a unique id for each entry in JSON object in JavaScript


In this problem statement, our task is to add a unique id for every object entry in a JSON object with the help of Javascript. So for doing this task we will use a loop and a variable to store the id for each object in the JSON object.

Understanding the problem statement

The problem statement is to write a function in Javascript by which we can add a unique id to every item in the given JSON object. For updating every JSON object by adding new id to every object we will use basic Javascript functionality. For example we have obj = {{empName: “A”, age: 25},{empName: “B”, age: 30}}, so after adding unique id to each entry updated objects will be as follows - obj = {{id: 0, empName: “A”, age: 25},{id: 1, empName: “B”, age: 30}}.

Logic for the given problem

So we will use an algorithm to assign a new id to every entry in the input JSON object. And this method will access a JSON object as an argument and we will use a for loop to traverse through every key in the object. So it will add a new property named id to the relevant item in the object for every key and set its value to a unique id value.

Step by step procedure

Step 1 − Create an object called jsonData and use an entry for defining each item in the object. inside the entry object define empName and age

Step 2 − Use addUniqueId function to create unique ids for each object in the data.

Step 3 − Initialize a variable called index to zero.

Step 4 − Loop through the JSON object with the help of a for loop.

Step 5 − Assign id to each entry in the JSON object by accessing every entry with dot notation or bracket notation.

Step 6 − After assigning id to each entry return the new JSON object with updated ids in each object

Code for the algorithm

const jsonData = {
   "entry1": {
      "empName": "Janvi",
      "age": 30
   },
   "entry2": {
      "empName": "Rani",
      "age": 25
   },
   "entry3": {
      "empName": "Babita",
      "age": 40
   }
   };
 
   // Function to add unique ID to JSON object
   function addUniqueId(jsonData) {
      let index = 0;
      for (let key in jsonData) {
         jsonData[key].id = index++;
      }
      return jsonData;
   }
const resultObject = addUniqueId(jsonData);
console.log(resultObject);

Complexity

The time taken by the algorithm is O(n), where n is the number of entries in the JSON object. Because the function needs to iterate over each entry in the object at once in order to add the unique ids. Space complexity of the algorithm is also O(n) because the function modifies the actual JSON object in place and does not create new data JSON.

Conclusion

The above code provides a simple solution to add a unique id for each entry JSON object in Javascript. So it has an O(n) time and space complexity which can make it less efficient for large JSON objects.

Updated on: 18-May-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements