Is there a method to swap out the current element in a JSON array with a new element based on a specific key?

My scenario involves handling a dynamic JSON array structured as follows:

let main_data = [
   {
      "client":[
         {
            "name":"aaaa",
            "count":"1",
            "filter":{
               "type":{
                  "name":"test3"
               }
            }
         },
         {
            "name":"bbbb",
            "count":"9",
            "filter":{
               "type":{
                  "name":"test2"
               }
            }
         }
      ]
   },
   {
      "compute":[
         {
            "name":"cccc",
            "count":"6",
            "filter":{
               "type":{
                  "name":"test"
               }
            }
         }
      ]
   }
]

Each key "name" is unique. When updating a form, I receive a JSON array like the one below:

let new_data = [
   {
      "client":[
         {
            "name":"bbbb",
            "count":"1234",
               "type":{
                  "name":"updated_name"
               }
            }
         }
      ]
   }
]

The task at hand is to identify the existing data with the same "name" in the "main_data" array, remove it, and replace it with the updated information provided in "new_data". (No jQuery solutions please)

The desired output should be as follows:

let main_data = [
   {
      "client":[
         {
            "name":"aaaa",
            "count":"1",
            "filter":{
               "type":{
                  "name":"test3"
               }
            }
         },
         {
            "name":"bbbb",
            "count":"123",
            "filter":{
               "type":{
                  "name":"updated_name"
               }
            }
         }
      ]
   },
   {
      "compute":[
         {
            "name":"cccc",
            "count":"6",
            "filter":{
               "type":{
                  "name":"test"
               }
            }
         }
      ]
   }
]

If there are any insights or suggestions on how to achieve this task efficiently, your assistance would be greatly appreciated. Thank you in advance.

Answer №1

Take a look at this solution

let data = [{
    client: [{
            name: "aaaa",
            count: "1",
            filter: {
                type: {
                    name: "test3"
                }
            }
        },
        {
            name: "bbbb",
            count: "9",
            filter: {
                type: {
                    name: "test2"
                }
            }
        }
    ]
},
{
    compute: [{
        name: "cccc",
        count: "6",
        filter: {
            type: {
                name: "test"
            }
        }
    }]
}
];
let newData = [{
client: [{
    name: "bbbb",
    count: "1234",
    filter: {
        type: {
            name: "updated_name"
        }
    }
}]
}];

const result = data.map((item, index) => {
if (item.client) {
    const clients = item.client.map(client => {
        if (client.name === newData[0].client[0].name) {
            client = newData[0].client[0];
        }
        return client;
    });
    return {
        client: clients
    };
}
return item;
});

console.log(result);

Answer №2

There might be a more complex method to accomplish this task, but one can simply identify the matching item and replace it accordingly. For example:

   let main_data = [
        {
            "client": [
                {
                    "name": "aaaa",
                    "count": "1",
                    "filter": {
                        "type": {
                            "name": "test3"
                        }
                    }
                },
                {
                    "name": "bbbb",
                    "count": "123",
                    "filter": {
                        "type": {
                            "name": "updated_name"
                        }
                    }
                }
            ]
        },
        {
            "compute": [
                {
                    "name": "cccc",
                    "count": "6",
                    "filter": {
                        "type": {
                            "name": "test"
                        }
                    }
                }
            ]
        }
    ];

    let new_data = [
        {
            "client": [
                {
                    "name": "bbbb",
                    "count": "1234",
                    "type": {
                        "name": "updated_name"
                    }
                }
            ]
        }
    ];

    console.log("before:" + JSON.stringify(main_data));

    newItem = new_data[0]["client"][0];
    mainDataList = main_data[0]["client"];

    for (i = 0; i < mainDataList.length; i++) {
        if (mainDataList[i].name == newItem.name) {
            mainDataList[i] = newItem;
        }
    }
    console.log("after:" + JSON.stringify(main_data));

Output will be as follows:

before:[{"client":[{"name":"aaaa","count":"1","filter":{"type":{"name":"test3"}}},{"name":"bbbb","count":"123","filter":{"type":{"name":"updated_name"}}}]},{"compute":[{"name":"cccc","count":"6","filter":{"type":{"name":"test"}}}]}]
after:[{"client":[{"name":"aaaa","count":"1","filter":{"type":{"name":"test3"}}},{"name":"bbbb","count":"1234","type":{"name":"updated_name"}}]},{"compute":[{"name":"cccc","count":"6","filter":{"type":{"name":"test"}}}]}]

Answer №3

If you're looking to update your main data with new information stored in a variable called newData, you can use this easy method:

main_data.client.filter(item => item.name === newData.name).push(newData)

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 displaying lesser-known checkboxes upon clicking a button in Angular

I have a form with 15 checkboxes, but only 3 are the most popular. I would like to display these 3 by default and have an icon at the end to expand and collapse the rest of the checkboxes. Since I'm using Angular for my website, I think I can simply ...

Effortless bug tracking in Chrome developer tools

When I'm debugging, I want the code to be displayed in Chrome browser (or another browser like Edge) exactly as it was written. Even when using pretty print, the code still appears unreadable. For example, a block of code written in my IDE: {provideD ...

Error encountered when attempting to upload image on Twitter: missing media parameter

According to the latest Twitter media upload API documentation, it is recommended to first utilize either POST multipart/form-data or base64 encoded files when interacting with . However, encountering an error with code 38 stating "media parameter is mi ...

Is there a way to create a function that is able to return both a value and a promise

Assume I need to fetch a value only if an object is already present in my model. Otherwise, I should retrieve the output of an endpoint service: model.getDoohkyById = function( id ){ if( this.data ) { if( this.data.length > 0) { ...

Tips for integrating H4 - H6 using a text editor in DNN7

It is essential for my client to have access to at least H4. Although I can add H4 to the ApplyClass menu in the text editor, it only applies a <span class="h4"> Sample </span> tag within the paragraph itself. Unfortunately, this method does ...

Arranging Multiple Files in Sequence Using HTML5 File API Instead of Uploading All Simultaneously

I am currently working on a BackboneJS/Marionette App and I want to enable users to upload multiple files. Right now, the functionality works when users select multiple files simultaneously, but I would like to give them the option to select one file init ...

Is there a way to customize the color of a MUI styled component?

I have a customized MUI component that displays a circular badge in green. const StyledGreenBadge = styled(Badge)(({ theme }) => ({ '& .MuiBadge-badge': { backgroundColor: '#44b700', color: '#44b700', ...

The React hamburger menu triggers a re-render of child elements within the layout

I am currently working with React and Material UI v5. Within my layout, I have a menu component with children. Whenever I click on the menu, it triggers a refresh of the children components. I attempted to resolve this by encapsulating the child components ...

Updating React state from another component - using useState

How can I efficiently update this state in React so that it changes when a specific button is clicked within the <FirstPage /> component? I'm struggling with finding the best approach to accomplish this. Any suggestions? const SignUp = () => ...

When attempting to retrieve the HTTP status, an ObjectDisposedException is returned

I'm having trouble retrieving the status code from an http response, like so: try { HttpWebRequest request = WebRequest.Create(requestURI) as HttpWebRequest; string text using (HttpWebResponse response = request.GetResponse() as HttpWebR ...

Locating elements with Selenium Webdriver using xpath

<a style="color:White;" href="javascript:__doPostBack('dnn$ctr674$Case$gvCaseSearchDetails','Page$777')">777</a> Can anyone help with writing an xpath for the HTML code above? The goal is to locate elements using the identi ...

Reimagining scrolling through content with a stylish unordered list (a sleek alternative to a select box

After having our company website redesigned by a professional designer, our site now looks much more visually appealing. However, I have encountered difficulties when trying to implement their design using HTML and CSS. One particular challenge is the heav ...

Exploring the Dynamic Resizing of Geometry Meshes in three.js

Is there a way to adjust the height of my geometry meshes dynamically? You can check out my demo here. ...

How can I verify the number of completed form fields?

I seem to be facing a minor issue: I have a webpage where users can input information into up to 10 fields. However, they are not required to fill out all 10 fields. Initially, the user is presented with only one field, and they have the option to add mor ...

What is the best way to store a file object in React's state?

I am currently working on setting the state for a file object that is being passed between modals before it is uploaded to the server. Below is the code snippet that demonstrates what I am attempting to achieve. const initialState = { selectedD ...

Unable to access $_POST parameters in PHP when making an Ajax request

My HTML file is shown below: <script> var xml = new XMLHttpRequest(); xml.onreadystatechange = function(){ if (xml.readyState === 4 && xml.status === 200) { console.log(xml.responseText); } } xml ...

What is preventing me from merging these two arrays together?

Here is some code for a Vuex mutation: export const CREATE_PANORAMAS = (state, panoramas) => { console.log('building.panoramas:', state.building.panoramas) console.log('panoramas:', panoramas) state.building.panoramas.concat(p ...

What is the reason behind the failure of next/script with Google reCAPTCHA?

Currently, I am in the process of upgrading from next js version 8 to version 11. I wanted to take advantage of the amazing next js feature for "next/script". However, when I tried to implement it for Google reCAPTCHA using "react-recaptcha": "^2.3.10", th ...

Navigating the grid layout in Material UI can be tricky to

I'm struggling to grasp the concept of the grid system in material UI. Within my grid container, I have two grid items that I want to be centered and occupy the entire width. The button element appears centered, but the typography element does not. A ...

What's the reason for text-alignment not functioning properly?

After some testing, I have come up with the following code: .Greetings { width:100%; display:block; text-align:center; font-family: "Times New Roman", Times, serif; font-size:75px; color:#208CB7; } The objective was to center the text on the ...