Update the JSON object with new data using JavaScript

After not receiving a proper response on my previous JSON replacement question, I am posting this follow-up query with a more detailed example.

var beforeReplacement=[
    {
        "Name": "app1",
        "id": "1",
        "groups": [
            {
                "id": "test1",
                "name": "test grp45",
                "desc": "this is a test group"
            },
            {
                "id": "test2",
                "name": "test group 2",
                "desc": "this is another test group"
            }
        ]
    },
    {
        "Name": "app2",
        "id": "2",
        "groups": [
            {
                "id": "test3",
                "name": "test group 4",
                "desc": "this is a test group"
            },
            {
                "id": "test4",
                "name": "test group 4",
                "desc": "this is another test group"
            }
        ]
    }
]


changed object:   
 [
        {
            "Name": "app2",
            "id": "2",
            "groups": [
                {
                    "id": "test3",
                    "name": "changed test group 4",
                    "desc": "this is a test group"
                }

            ]
        }
    ]





 var afterReplacement=[
        {
            "Name": "app1",
            "id": "1",
            "groups": [
                {
                    "id": "test1",
                    "name": "test grp45",
                    "desc": "this is a test group"
                },
                {
                    "id": "test2",
                    "name": "test group 2",
                    "desc": "this is another test group"
                }
            ]
        },
        {
            "Name": "app2",
            "id": "2",
            "groups": [
                {
                    "id": "test3",
                    "name": "changed test group 4",
                    "desc": "this is a test group"
                },
                {
                    "id": "test4",
                    "name": "test group 4",
                    "desc": "this is another test group"
                }
            ]
        }
    ]

I updated the name in var beforeReplacement and provided details of the modified object to be received. How can I efficiently replace this changed object in the beforeReplacement array, resulting in an object similar to var afterReplacement?

Answer №1

let newSet = oldSet.map(function (item) {
    for(let key in replacements) {
        if (replacements[key].id !== item.id) continue; 

        item = replacements[key];
        break;
    }
    return item;
});

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

Trouble with an external .js script

function displayMessage() { var isConfirmed = confirm("Do you want to proceed?"); if (isConfirmed) { window.location = "./proceed"; } }; function checkIfEmpty(){ console.log("checkIfEmpty"); }; @CHARSET "ISO-8859-1"; form { margin:0 auto; width:300px ...

Important notice: It is not possible to assign refs to function components. Any attempt to do so will result in failure. If you intended to assign a ref, consider

My console is showing a warning when I use the nextJs Link component. Can someone assist me in resolving this issue and providing an explanation? Here is the message from the console: https://i.stack.imgur.com/jY4FA.png Below is a snippet of my code: im ...

Navigating the world of cryptocurrency can be daunting, but with the right tools

Hello fellow developers, I've encountered some difficulties with cryptocurrency in my Nativescript project. I am attempting to incorporate the NPM package ripple-lib into my code, but I have been unsuccessful using nativescript-nodeify. How can I suc ...

Guide on how to retrieve a server-generated message within a jQuery script on an EJS page

Is there a way to retrieve and utilize a variable passed from a controller to an EJS page in a jQuery script? Below is the code snippet for reference: app.get('/form', (req, res) => { res.render('form', { errorMessage: & ...

Is it possible to retrieve the object from a forEach loop?

Can an object be built using the results of a forEach loop? Here's my current approach: const data = {} object.rules.forEach(rule => { data[rule.name] = { body: [], type: rule.type } }) This is how I'd prefer to do it: const newData = obj ...

Tips for programmatically focusing on a v-textarea using Vuetify and TypeScript

It feels impossible right now, I've attempted some unconventional methods like: (this.refs.vtextarea as any).textarea.focus() ((this.refs.vtextarea as Vue).$el as HTMLElement).focus() and so on... Javascript source code is quite complex for me to ...

Converting a JSON array into a Java HashMap with Jackson: A step-by-step guide

I would like to use Jackson to convert the JSON array below into a Java HashMap, and then iterate over the values as shown: Desired output format: key Value 1 sql 2 android 3 mvc JSON Sample: enter code here { "menu": [ { ...

guide on executing a function for dynamically added selections

When dynamically adding HTML elements to the page, I encountered an issue where using a "bind" wasn't practical due to multiple items being added at different times. As a solution, I opted for an inline function, which unfortunately only worked on bro ...

JavaScript Lightbox for Full Page Content (or near full page)

One option to consider is always jQuery. I am in search of a lightbox that provides a "full screen" effect. Not necessarily filling the entire screen, but rather covering most of the content on the page. The lightboxes I have come across either only displ ...

Tips for retrieving the value of an array element from a JSON-decoded object using cURL

I am attempting to retrieve the value of the first element, [0]['uri'] from the result of my API call using cURL. I have received an associative array from the curl_exec function but am struggling to extract the data in order to find the value of ...

Error: the variable "ionic" has not been properly declared and defined

When testing the Ionic app, an error message "Uncaught ReferenceError: ionic is not defined" appears when opened in a browser. Additionally, the app shows a blank screen on mobile devices. Is there a solution to fix this issue? ...

Convert JSON object to a string representation

I am attempting to print a JSON object in string format. (I actually retrieved these data values from Ruby code var data = '<%=[@pro {|c| {x:c.x, y:c.y}}].to_json%>') When printing the data variable, I noticed that the values contain & ...

Tips for fixing issues with JSONParser() function

My current challenge involves attempting to access a json file in Java. Here is the progress I've made so far: import jdk.nashorn.internal.parser.JSONParser; import java.io.FileReader; import java.util.Objects; public static void main (String[] ...

A helpful guide on performing a service call in AngularJs when attempting to close the browser tab or window

I am currently working on implementing a service call that will trigger when the browser tab or window is being closed. I was wondering if there is a way to make a RestApi call when attempting to close the browser tab or window. Does anyone have any sugge ...

Can the use of setTimeout alter global variables?

let currentVariable = 'ye'; setTimeout(()=>{ currentVariable = 'lin' },2000) Hey everyone, I have a question. Initially, I set a variable currentVariable to "ye", and then in a setTimeout function I change it to "lin" after 2 s ...

The initial invocation of the JavaScript function did not run

In my Grails view, I have a script tag set up like this: <script type="text/javascript"> /* the first setInterval */ setInterval( function() { console.log("Test..."); }, 5000 ); setInterval( ...

Issues with Jquery and revslider functionality in React.js are causing problems

Just getting started with react.js and diving into the world of react development. Encountering an issue while converting static HTML to react.js where jQuery scripts only execute after manually refreshing the page, causing a slowdown in React speed. T ...

Capturing data through Facebook's OAuth authorization

I have been trying to retrieve Oauth data from Facebook and store it in my table. Here is the code I have written: $app_id = "340088232675552"; $canvas_page = "https://apps.facebook.com/appluckyprice/index.php"; $auth_url = "https://www.facebook.com/dialo ...

Mastering the Art of Parsing Complex JSON Data

I received a JSON output that looks like this. Using getjson, I'm trying to extract the datetime and value fields (italicized and bolded) such as [16:35:08,30.579 kbit/s],[16:35:38,23.345 kbit/s]. Is there any solution to achieve this? Thank you. { ...

Angular4 allows for the creation of a div that can horizontally scroll

Below is the HTML code I am working with: <div class="card-deck" fxLayout.xs="row" style="overflow: scroll; height:100%"> <md-card style="width:10rem" *ngFor="let make of filteredMakes" (click)="goToModels(make.niceName)" class=" ...