Revamping JSON structure by identifying id references

I recently attempted to update the city name within the JSON object provided below.


    "City":[
   {
      "Name":"Delhi",
      "id":"c5d58bef-f1c2-4b7c-a6d7-f64df12321bd",
      "Towns":[
         {
            "Name":"MG Colony",
            "conditionId":"60d1f5eb-0222-4a84-879b-6699b0cfc1a4",
            "cid":"c5d58bef-f1c2-4b7c-a6d7-f64df12321bd"
         },
         {
            "Name":"DLF Colony",
            "conditionId":"60d1f5eb-0222-4a84-879b-7749b0cfc1a4",
            "cid":"c5d58bef-f1c2-4b7c-a6d7-f64df12321bd"
         }
      ]
   },
   {
      "Name":"Pune",
      "id":"c5d58bef-f1c2-4b7c-a6d7-f64df12321ax",
      "Towns":[
         {
            "Name":"Hadapsar",
            "conditionId":"60d1f5eb-0222-4a84-879b-6699b0cfc1x4",
            "cid":"c5d58bef-f1c2-4b7c-a6d7-f64df12321ax"
         },
         {
            "Name":"Magarpatta",
            "conditionId":"60d1f5eb-0222-4a84-879b-7749b0cfc1f4",
            "cid":"c5d58bef-f1c2-4b7c-a6d7-f64df12321bax"
         }
      ]
   }
]

My goal was to replace the town name from "Hadapsar" to "Viman Nagar" if the cid matched that of Hadapsar Town

The desired output was:


   "City":[
   {
      "Name":"Delhi",
      "id":"c5d58bef-f1c2-4b7c-a6d7-f64df12321bd",
      "Towns":[
         {
            "Name":"MG Colony",
            "conditionId":"60d1f5eb-0222-4a84-879b-6699b0cfc1a4",
            "cid":"c5d58bef-f1c2-4b7c-a6d7-f64df12321bd"
         },
         {
            "Name":"DLF Colony",
            "conditionId":"60d1f5eb-0222-4a84-879b-7749b0cfc1a4",
            "cid":"c5d58bef-f1c2-4b7c-a6d7-f64df12321bd"
         }
      ]
   },
   {
      "Name":"Pune",
      "id":"c5d58bef-f1c2-4b7c-a6d7-f64df12321ax",
      "Towns":[
     {
            "Name":"Viman Nagar",
            "conditionId":"60d1f5eb-0222-4a84-879b-6699b0cfc1x4",
            "cid":"c5d58bef-f1c2-4b7c-a6d7-f64df12321ax"
         },
         {
            "Name":"Magarpatta",
            "conditionId":"60d1f5eb-0222-4a84-879b-7749b0cfc1f4",
            "cid":"c5d58bef-f1c2-4b7c-a6d7-f64df12321bax"
         }
      ]
   }
]

I attempted to use JavaScript's map function for iteration but faced challenges in replicating the exact structure.

Answer №1

It appears that using only the map method may not be sufficient to address your issue, particularly due to the presence of nested arrays. Have you considered utilizing the map method twice instead? Here's an example scenario:

var cid = "c5d58bef-f1c2-4b7c-a6d7-f64df12321ax";
var newName = "Viman Nagar";
City = City.map(function(city) {
  city.towns = city.towns.map(function(town) {
    if (town.cid === cid)
      town.name = newName;
    return town;
  });
  return city;
});

Answer №2

Declare your array as

const locations = [{
    "City": "Mumbai"
     ...
}]

and proceed to iterate through it

let updatedLocations = locations.map(location => location.Areas.map(area => {
    if (area.Name === "Andheri") {
        return {
            ...area,
            Name: "Bandra"
        }
    } else return area
}))

Answer №3

Utilize Array#map in the following manner:

  • Go through each item in the array cities
  • For each iteration, go through the array Towns. If the current town's cid matches the one to be changed, update its Name

const changeTownName = (cities = [], cid, name) =>
  cities.map(({ Towns = [], ...props }) => ({
    ...props,
    Towns: Towns.map(town => town.cid === cid 
      ? { ...town, Name: name } 
      : { ...town }
    )
  }));

const cities = [
  { Name: 'Delhi', id: 'c5d58bef-f1c2-4b7c-a6d7-f64df12321bd', Towns: [ { Name: "MG Colony", conditionId: '60d1f5eb-0222-4a84-879b-6699b0cfc1a4', cid: 'c5d58bef-f1c2-4b7c-a6d7-f64df12321bd' }, { Name: "DLF Colony", conditionId: '60d1f5eb-0222-4a84-879b-7749b0cfc1a4', cid: 'c5d58bef-f1c2-4b7c-a6d7-f64df12321bd' } ] },
  { Name: 'Pune', id: 'c5d58bef-f1c2-4b7c-a6d7-f64df12321ax', Towns: [ { Name: "Hadapsar", conditionId: '60d1f5eb-0222-4a84-879b-6699b0cfc1x4', cid: 'c5d58bef-f1c2-4b7c-a6d7-f64df12321ax' }, { Name: "Magarpatta", conditionId: '60d1f5eb-0222-4a84-879b-7749b0cfc1f4', cid: 'c5d58bef-f1c2-4b7c-a6d7-f64df12321bax' } ] }
];
console.log( changeTownName(cities, 'c5d58bef-f1c2-4b7c-a6d7-f64df12321ax', 'Viman Nagar') );

Answer №4

For those looking to transform a city into cities, here is some helpful code:

cities.forEach(city => {
    city.Towns = city.Towns.map(el => {
        if (el.Name === 'Hapdasar') {
            el.Name = 'Viman Nagar';
        }
        return el;
    })
});

Answer №5

Make sure to iterate through each city and its corresponding towns in the array. If the town's cid matches the specified cid, update the town's name with the new one provided;

const myNewTownName = "Central City";
const cid = "a1b2c3d4-e5f6-7g8h9-i0j1k2l3m4n5;
for(let i = 0; i < myObj.Cities.length; i++){
    const city = myObj.Cities[i];
    for(let j = 0; j < city.Towns.length; j++){
        const town = city.Towns[j];
        if(cid === town.cid){
            town.Name = myNewTownName;
        }
        city.Towns[j] = town;//Update city with the modified town
    }
    myObj.Cities[i] = city; //Update myObj with the modified city
}

Answer №6

One way to achieve the desired result is by utilizing nested .forEach loops to iterate through both the outer and inner arrays. An if block can then be used to inspect the cid value for the specified town.

const data = {
"City":[
   {
      "Name":"Delhi",
      "id":"c5d58bef-f1c2-4b7c-a6d7-f64df12321bd",
      "Towns":[
         {
            "Name":"MG Colony",
            "conditionId":"60d1f5eb-0222-4a84-879b-6699b0cfc1a4",
            "cid":"c5d58bef-f1c2-4b7c-a6d7-f64df12321bd"
         },
         {
            "Name":"DLF Colony",
            "conditionId":"60d1f5eb-0222-4a84-879b-7749b0cfc1a4",
            "cid":"c5d58bef-f1c2-4b7c-a6d7-f64df12321bd"
         }
      ]
   },
   {
      "Name":"Pune",
      "id":"c5d58bef-f1c2-4b7c-a6d7-f64df12321ax",
      "Towns":[
         {
            "Name":"Hadapsar",
            "conditionId":"60d1f5eb-0222-4a84-879b-6699b0cfc1x4",
            "cid":"c5d58bef-f1c2-4b7c-a6d7-f64df12321ax"
         },
         {
            "Name":"Magarpatta",
            "conditionId":"60d1f5eb-0222-4a84-879b-7749b0cfc1f4",
            "cid":"c5d58bef-f1c2-4b7c-a6d7-f64df12321bax"
         }
      ]
   }
]

} // end data;


const targetCid = "c5d58bef-f1c2-4b7c-a6d7-f64df12321ax"; // cid for Hadapsar;

const objArray = data.City;

objArray.forEach(element => {
  
  element.Towns.forEach(element => {  
  
    if (element.cid == targetCid) {
      element.Name = "Viman Nagar";
    } // end if;
  
  }); // next object in Towns array;

});  // next object in objArray;
  


document.getElementById('output').textContent = JSON.stringify(data, undefined, 2);
#output {
 white-space: pre;
}
<pre id="output"></pre>

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

Tips for fading out two elements after completing a drag and drop action

Visit this Codepen for more examples - Codepen I have been developing a drag and drop feature in my application. Once the item is dropped, it transitions from red to green and fades out smoothly. The droppable element behind the draggable should also fad ...

Selenium - Activating a flash button

Currently, I am facing an issue while trying to load a URL using Selenium on Mozilla browser. The webpage contains a 'Login' button created in flash that I need to click on. I have explored the following resources: 1.How to click an element in Se ...

Transmitting an HTML file along with JSON data and enabling the browser to refresh the JSON data without reloading the entire

I'm currently working on a project involving a browser-server program where the browser sends an http get request to ''. The server is expected to return both an HTML page and a JSON response. I attempted using res.render(), passing the JSON ...

PHP web service login portal

if($_SERVER['REQUEST_METHOD'] == "GET"){ // Retrieving post data $username = isset($_POST['username']) ? mysql_real_escape_string($_POST['username']) : ""; $password = isset($_POST['password']) ? mysql_real_escape_st ...

Is the Site Header displayed depending on the scroll position and direction of scrolling?

On my website, I have a header that I want to hide when the user scrolls down 100px and show again when they scroll up 50px. I attempted to write a script for this functionality, but it doesn't seem to be working as expected. CSS /* This CSS rule w ...

Fixing the issue of 'Unrecognized character < in JSON at position 0 at JSON.parse'

I have recently deployed my Angular 6 application on Heroku at . However, upon deploying, I encountered the error message: SyntaxError: Unexpected token < in JSON at position 0 during JSON.parse. I am aware that this error occurs when the response ret ...

AngularJS - Organize Item Hierarchy with Separate Containers for Each Group

My goal is to incorporate a $scope variable within an AngularJS controller that has the following structure: $scope.hierarchy = { name: 'bob', selected: true, children: [ { name: 'frank' }, { name: 'spike' ...

What could be the reason for the error message when using rs.send with a string input?

I'm a beginner in node and express, and I was trying to create an HTML form that takes two numbers and displays the result using "express" and "node". However, when I use rs.send(result), I encounter the following error: This error message appears on ...

The conditional rendering issue in Mui DataGrid's renderCell function is causing problems

My Mui DataGrid setup is simple, but I'm encountering an issue with the renderCell function not rendering elements conditionally. The default behavior should display an EditIcon button (the pencil). When clicked, it triggers the fetchSomething functi ...

Convert an R data frame into a simple JSON format

I'm looking to convert a basic data frame in R into a plain JSON object and add multiple variables to a data.js file. Here's the data frame I want to work with: df <- data.frame(Person=c("Dan", "Tom", "Max"), Apples=c(3,5,8), Pears=c(1,0,2), ...

Ways to display a price near a whole number without using decimal points

Currently, I am working on an ecommerce project where the regular price of an item is $549. With a discount of 12.96% applied, the sale price comes down to $477.8496. However, I want the sale price to be displayed as either $477 or $478 for simplicity. Yo ...

What could be the reason for JSON.parse not returning the expected outcome?

My code is as follows: var jsonStr = (JSON.stringify(data, ['flightPositions', 'flightId', 'positions', 'lat', 'lon', 'date'], 4)); alert(jsonStr); var jsonObj = JSON.parse(jsonStr); alert(jsonO ...

The process of integrating a Loader in Javascript

I am in need of a simple "page loading" animation while my photo is being uploaded. Unfortunately, when I tried using the "blockUI" JavaScript for this purpose, it didn't seem to work with my form. For uploading the image, I have employed a div as a ...

Creating controller functions for rendering a form and handling the form data

When developing a web application using Express.js, it is common to have separate controller functions for rendering forms and processing form data. For instance, if we want to import car data from the client side, we might implement the following approach ...

Tips for incorporating a Forgot/Reset password option into your #Firebase platform

In the project I'm working on, I am utilizing #AngularFire2. My goal is to incorporate a Reset / Forgot password link into the login page. Does anyone have suggestions on how to accomplish this task? I'm looking to get some insights from #AskFi ...

Can a PHP script be executed through an Ajax event?

Is it feasible to execute the script of a PHP file when an AJAX event is triggered? Consider this scenario: on the AJAX error, could we send the data to the error.php file, record the error, notify the admin via email, and perform any other desired action ...

Creating a selectAll checkbox that triggers the ng-click function on each individual checkbox

I've encountered an issue with my code where clicking a checkbox triggers the ng-click function. Here is the JavaScript snippet: $scope.selectTitle = function(evt, selected){ evt.stopPropagation(); var filtered = _.findWhere($scope.se ...

I seem to be having trouble properly parsing JSON data with the Gson library

Seeking assistance with reading JSON using the Gson library, encountering an Exception: Exception in thread "main" com.google.gson.JsonSyntaxException: java.io.EOFException: End of input at line 1 column 2 path $. Java class definition class Data { ...

React error: "Unable to locate property 'bind' within the undefined"

After reviewing several solutions, I'm still struggling to understand. Below is my code snippet: // userInputActions.js ... export function dummy() { console.log('dummy function called'); } ... // *userInputPage.js* import * as use ...

Using JQuery to eliminate the current div in an image slider

I currently have an image slider that allows users to switch between images. There are two buttons - one adds a new item to the slider, while the other is supposed to remove the current image from the slider, but it doesn't seem to be working properly ...