Store a JSON object without creating a reference to it

My issue is presented in a much simpler manner.

Here is the json (you can view it here if you wish)

{"resource":[{"id":"1408694994","obj":[{"id":"1","action":[{"name":"ON","id":"301"},{"name":"OFF","id":"302"}]},{"id":"2","action":[{"name":"ON","id":"303"},{"name":"OFF","id":"304"}]}]},{"id":"1408694995","obj":[{"id":"3","action":[{"name":"ON","id":"305"},{"name":"OFF","id":"306"}]},{"id":"4","action":[{"name":"ON","id":"307"},{"name":"OFF","id":"308"}]}]}]}

If given an ID (in this case, let's say ID = 3), I need to save the item with that ID. Then, I must store in a new object (newobj) the object with that ID, but changing the array ACTION to an OBJ with only the action ON.

Illustration

<script> 

    var tt = '{"resource":[{"id":"1408694994","obj":[{"id":"1","action":[{"name":"ON","id":"301"},{"name":"OFF","id":"302"}]},{"id":"2","action":[{"name":"ON","id":"303"},{"name":"OFF","id":"304"}]}]},{"id":"1408694995","obj":[{"id":"3","action":[{"name":"ON","id":"305"},{"name":"OFF","id":"306"}]},{"id":"4","action":[{"name":"ON","id":"307"},{"name":"OFF","id":"308"}]}]}]}';

    var myjson = JSON.parse(tt);

    var search = 3;


    console.log(myjson.resource[1].obj[0]);

    for(var i = 0 ; i < myjson.resource.length; i++){

        for(j = 0 ; j < myjson.resource[i].obj.length; j++){

            if(parseInt(myjson.resource[i].obj[j].id) == search){

                var newobj = myjson.resource[i].obj[j];

                var obj_action = newobj.action;
                for(var k = 0 ; k < obj_action.length ; k++){

                    if(obj_action[k].name == "ON"){
                        newobj.action = obj_action[k];
                    }
                }
            }   
        }
    }

    console.log(myjson.resource[1].obj[0]);

</script>

I am able to successfully save the desired object in the newobj variable. However, why does the original JSON get altered?

UPDATE

It appears that the issue lies in how I'm storing the obj in the newobj variable. It seems like I'm saving a reference to the object in the JSON rather than the object itself. How can I save it in the newobj variable without creating a reference?

Answer №1

To create a separation between object references, an effective method is to utilize serialization and deserialization in the form of JSON. A practical application of this concept would involve implementing the following code:

let newObj = JSON.parse(JSON.stringify(myJSON.resource[i].object[j]));

It should be noted that this approach may not be suitable for all scenarios. Objects containing intricate functions or prototypes may not be accurately preserved.

In addition, there may be a minor impact on performance when using this technique.

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

Is the RouterModule exclusively necessary for route declarations?

The Angular Material Documentation center's component-category-list imports the RouterModule, yet it does not define any routes or reexport the RouterModule. Is there a necessity for importing the RouterModule in this scenario? ...

Switch between divs based on the current selection

var header = $("#accordion"); $.each(data, function () { header.append("<a id='Headanchor' href='javascript:toggleDiv($(this));'>" + this.LongName + "</a>" + "<br />", "&l ...

What does it mean in Javascript when b1 is undefined while o1 has a value and is equal to b1?

Having some issues getting variables to work with drop down options on a page. At first, I couldn't even extract a value from the function but managed to do so by removing "var" from o1. Strange thing is, when I type o1 into the js console on chrome i ...

Issue with Angular 8: click event is not triggering when using ngFor directive to iterate through arrays of objects

Update: The original post has been modified to omit implementation details and complexity. I am facing an issue with an ngFor loop that invokes a method on a service. The method returns an array which is then iterated over by the for loop. The click even ...

During the bulk insert process, only a portion of the BinaryDocument(s) are successfully uploaded into the system

I've encountered a strange issue with document insertion. I am working with two types of documents - JSON and BinaryDocument - and performing bulk insert operations with a specific batch size limit. The problem arises when inserting BinaryDocuments. ...

HTML Scripts: Enhancing Web Functionality

I have another question regarding executing a script (docs()) upon clicking on text. I attempted to use the following code: <p><span class="skill">Documentation can be found here.<script>docs()</script></span></p> Unfo ...

What is the best approach for designing the architecture of a server-side node.js application?

Can you recommend a suitable architecture or pattern for building server-side applications using node.js? For the front-end, I plan on implementing a backbone.js MVC framework and utilizing websockets for communication. If you could provide some examples ...

The webpage loaded through ajax is not rendering correctly

One of the challenges I'm facing is getting a JavaScript script to load an HTML page into a specific div element on another HTML page: The page that's being loaded, startScreen.html, looks like this: <!DOCTYPE html> <html lang="en ...

Exploring the concept of generator functions in ES6

I'm grappling with understanding JS generators and why the asynchronous operations in the example below are returning undefined. I thought that using yield was supposed to wait for asynchronous calls to finish. function getUsers(){ var users; $.aj ...

Exploring ways to loop through objects in a React application

I'm trying to figure out how to modify the code below to iterate through a custom object I have created. function itemContent(number) { return ( <div > <div className="item"> <div className="itemPic& ...

What steps are necessary to integrate expo-auth-session with Firebase?

I am working on implementing a feature in my code that will allow users to login and authenticate using their Google credentials. Once they successfully log in, I want them to be added to my authentication database in Firebase. My attempt to achieve this ...

Why is it that a click event outside of an HTML element cannot be detected in this Vue 3 application?

I've been diving into building a Single Page Application using Vue 3, TypeScript, and The Movie Database (TMDB). Currently, I'm focused on developing a search form within my project. Within the file src\components\TopBar.vue, here&apo ...

Having trouble with displaying the modal dialog in Twitter Bootstrap 3?

There seems to be an issue with my Twitter Bootstrap modal as it is not rendering the dialog box correctly, and I'm puzzled about the reason behind this. HTML <p class="text-center btn-p"><button class="btn btn-warning" data-toggle="modal" ...

What are the steps to enable a Vue component to handle its own transitions?

I am looking for a way to handle enter and leave animations in Vue when components are mounted or removed. My goal is to consolidate all the animation code into its own component for better organization. <template> <transition @enter="enter" ...

The resolution of Angular 8 resolver remains unresolved

I tried using console.log in both the constructor and ngOnInit() of Resolver but for some reason, they are not being logged. resolve:{serverResolver:ServerResolverDynamicDataService}}, console.log("ServerResolverDynamicDataService constructor"); console ...

Tips for sending a localstorage value as a parameter in an axios request

Currently, in my React app, I am using Express to handle all of my database queries. One thing I am attempting to achieve is passing the user id stored in local storage into a post request. This is necessary for my application since it revolves around use ...

Using jQuery to Post JSON

I need help with implementing an ajax call that sends data in JSON format. There seems to be a syntax error in my code. For example: var string_json='{"usr":{"name":"john","surname":"do"}}'; $.ajax({ url:"myurl",type:"post",data:{user:JSON.strin ...

How can socket listener be dynamically added in node.js with socket.io?

Assuming you have a basic socket.io configuration set up: var app = require('http').createServer().listen(80,'127.0.5.12'), io = require('socket.io').listen(app); session = require('./local_modules/session.js'); / ...

VueJS Error: Attempting to access a property that is undefined causing a TypeError (reading 'toLowerCase')

Whenever I attempt to filter and remove items from an array, everything works fine. However, when I try to add new items to the array, I encounter an error message that says "TypeError: Cannot read properties of undefined (reading 'toLowerCase'). ...

What is a more efficient method for structuring this React page while making an asynchronous request to the API?

When developing, I encountered this scenario where I needed to ensure that a certain useEffect function only runs once. To achieve this, I established router.query.something as a dependency for the effect. The logic is such that the request will only trigg ...