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 avoiding simultaneous state transitions in Angular UI Router

My situation in my Angular application involves a frustrating issue. Whenever a user double-clicks quickly on a link to a specific state (ui-sref link), the target state starts loading twice. This would be manageable if the state window didn't freeze ...

Error: JSDOM - The document variable has not been declared

After creating a basic webpage that displays a single message, I decided to experiment with JSDOM and encountered an error. Despite researching online examples and Stack Overflow questions, I have struggled to resolve even the most straightforward scenario ...

Loop through each HTML element and store it in a JavaScript array

I currently have a webpage with 3 select buttons named "Season". I am trying to figure out which buttons are selected and receive their values as an array on my webpage. Below is the code I am using: var season_array = $.each($(form).children("input.sele ...

The issue arises when the logout component fails to render even after the user has been authenticated. This problem resembles the one discussed in the React Router

While attempting to run the react-router docs example on the browser, I encountered an issue with the AuthButton component. The problem arises when the isAuthenticated value changes to true but the signOut button fails to display. import React from ' ...

Tips for resolving the issue: SyntaxError - Unexpected token import

I've encountered this error in the past and have looked at other solutions, but none of them seem to work for my specific issue. My package.json file includes the following dependencies: "dependencies": { "axios": "^0.15.2", "babel": "^6.5. ...

After resizing, reordering, hiding, or showing columns in the kendo grid, the grid's data source will be set to

I am encountering an issue with my kendo grid where the data disappears after performing certain actions: Reordering columns using mouse drag and drop Resizing columns using mouse drag and drop Hiding columns through the column menu Showing columns throu ...

Using jQuery idle timeout to abort jQuery AJAX calls in Laravel 5.2

Currently, I have implemented the jQuery Idle Timeout plugin in my Laravel 5.2 system. Everything works perfectly on my local setup using MAMP Pro, but upon uploading it to the development server, I encountered an "Aborted" error in the AJAX get request: ...

What is the significance of declaring a constant array in JavaScript?

Does declaring an array as a constant in JavaScript prevent it from changing size, or does it mean that the values inside the array cannot be modified? handleClick(i) { const squares = this.state.squares.slice(); squares[i] = 'X'; this.setState( ...

ajax is triggering the error handler

I am currently developing a web application and I am trying to send data from a PHP controller to JavaScript. After conducting some research, it seems that the most efficient way to accomplish this is by utilizing Ajax and Json. However, I am encountering ...

Tips for formatting the body of a post request

After sending a data from a nodejs server Using POST REQUEST { "id": "285104348274884628", "username": "TEST USERNAME", "apiKey": "5WA8G5LUYPJB8RII64RE443EFTTY-PY" } The Post Code In ...

Update the headers of the axios.create instance that is exported by Axios

I have a single api.js file that exports an instance of axios.create() by default: import axios from 'axios' import Cookies from 'js-cookie' const api = axios.create({ baseURL: process.env.VUE_APP_API_URL, timeout: 10000, headers ...

Including a hyperlink in VUE Bootstrap for seamless user navigation

Why does this always drive me crazy? I'm determined to include an external link () and an image(enter image description here) on my portfolio page within the title of the project. main.js { id: 18, url: 'single-portfolio. ...

Exploring the possibilities of node-webkit: node-odbc encounters a setback

Currently, I'm in the process of developing a desktop application utilizing node-webkit. The main functionality of the app involves querying an Oracle database. To establish the connection with the database, I have integrated node-odbc. To ensure tha ...

Is it possible to animate multiple SVGs on a webpage with just the click of a button?

Is there a way to trigger the animation in the SVG each time a next/prev button is clicked while navigating through a carousel where the same SVG is repeated multiple times? The carousel is built using PHP and a while loop. jQuery(document).ready(function ...

Guide on using jq to parse an array of JSON objects

I have a Json file that contains multiple arrays. Here is an example of the json source: { "iabVersion": "IAB_V2", "categories": [{ "categories": [{ "categories": [{ "id": "1.1.1", "name": "Commercial Trucks" } ...

A guide to playing a series of audio files in succession using the Ionic Media plugin

I have been attempting to create a playlist of multiple audio files using the Ionic media plugin from here. However, I am struggling to achieve this without resorting to using a timeout function. Here is my current approach: playOne(track: AudioFile): Pr ...

Having trouble with React button conditional rendering not functioning properly

Currently, I am working on a cart application and facing an issue. The problem is that the button is not getting disabled when the quantity reaches zero. Instead, it continues to show the 'add to cart' button even when no items are left in stock. ...

Combining items from the identical array in pairs using distinct identifiers

I have an array containing double values. const data = [ -0.003,-8.178509172818559E-16, 0.002,-1.3576469946421737E-15, 0.007,-1.2329107629591376E-1] I am looking to utilize these values in react-vis. The necessary syntax for data insertion in react-vis ...

Angular Material Popup - Interactive Map from AGM

I am in the process of developing a material dialog to collect user location information using AGM (angular google maps). I have successfully implemented a map on my main page, but when the dialog is opened, it only shows a blank space instead of the map. ...

Step-by-step guide on utilizing User scripts with the $window.open function in AngularJS

I am looking to initiate the following action - (for example: Upon clicking a button, it should direct to this , similar to how payment gateways function) and then, I need to input the user script below: getRealData('{"mailing":{"postalCode":"1 ...