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

Implementation of internationalization into a JSON-formatted data file

I recently integrated i18n into my application and I'm facing a challenge with implementing the useTranslation(); function in my navbar data file. This file serves as the database for the page titles and tabs, and I'm unsure about how to proceed. ...

Retrieving the value of an item within a string array using VB.NET

Here is the code snippet I am working with: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim JsonSub As String = "{""subdomain01"":[""21"",""subdomain01"",""4""],""subdomain02"":[""22"","" ...

Issue with React Redux: Passing down a component's method to its children results in an undefined error

Currently, I am working on creating a todo list using React and Redux. In my code snippet provided below, there is a component that includes a function called onDeleteItem. The issue I am facing is the inability to pass the onDeleteItem function to the s ...

Adding a Sequence of Class Names to <li> Elements with JavaScript

How can you easily generate sequential class names in a for loop? ...

What steps can I take to ensure the browser only shows the page once it has completely loaded?

I find it frustrating when webpages load slowly and you can see the process happening. In my opinion, it would be more satisfying to wait until everything is fully loaded - scripts, images, and all - before displaying the page. This brings up two questio ...

Strategies for resolving minor validation challenges (Almost complete, just a few finishing touches needed ...)

This question was originally posted in Spanish on es.stackoverflow.com by Julian Dumitrel: I had planned to make a record, step by step, where I had 3 different steps all within one <form>. After finishing my form validator successfully, I encounte ...

Converting a Pandas DataFrame to JSON converts the index into dot notation

I am facing an issue with converting a Pandas DataFrame into JSON. The to_json() method works fine, but it changes the DataFrame index to strings (e.g. 0 is converted to "0.0") instead of just "0". This is not the desired outcome for me. The DataFrame is ...

Fetch several images simultaneously from a photo collection using JavaScript by generating a batch process

I need help with creating an image gallery that allows users to download multiple images by selecting them. The download should result in a zip file. I have checkboxes for selecting the images, but I'm struggling to figure out how to enable the downlo ...

What is the comparable javascript code for the <script src="something1.json"></script> tag?

Within my HTML code, I currently have the following line to read a JSON file: <script src="something1.json"></script> Inside this JSON file, there is a structure like so: var varName = { .... } This method of definition naturally sets up ...

Activate or deactivate a text box within a table based on the checkbox's status

I am seeking assistance with jQuery to enable or disable a textbox within a table when a checkbox is checked. Below is the code snippet from my edit.cshtml file. <table id="scDetails" class="dataTable"> <thead> & ...

There was an error with the response code of 500 on the development server for react-native

An issue has been encountered on the node.js window: error: bundling failed: Error: Unable to resolve module react-native-gesture-handler from node_modules\@react-navigation\native\src\Scrollables.js: react-native-gesture-handler could ...

load a particular section of another website into my own div

Similar Question: Ways to bypass the same-origin policy I've been looking for a way to load a specific div from another website using this code. Can anyone provide an example of how to do this on jsfiddle? $.ajax({ url: 'http://somethin ...

Loading Data into Array - Angular/Ionic

I am currently developing an App and encountering issues with pushing data into an array. It seems that there is a problem in my code. Would you mind taking a look? Error Message Thrown: ionic.bundle.js:25642 TypeError: Cannot read property 'title&ap ...

Ways to Determine if a User Has Closed the Page

How can I detect when a user closes the page without using the back button or typing in a different URL in the address bar? I've attempted to use the following code: $(window).bind('beforeunload', function () { logout(); }); This solutio ...

I require assistance in troubleshooting and repairing my HTML and JavaScript code

I am working on creating a feature where users can input their upcoming birthday date and receive an alert showing how many days are left until then. However, I encountered an issue where the alert displays NaN (Not a Number) before the birthday is entered ...

What is the most elegant way to retrieve a new item from Firebase and read it?

My goal is to display the result of a successful read on a page, with only one attempt available before the headers are set and the page is sent. I am looking to retrieve one new value, generated after a listener was initiated so as not to pull existing da ...

Bootstrap alert JS refuses to slide down

Here is the JavaScript code to make a blue bar slide down on click: $('#comment').click(function(e) { e.preventDefault(); $('#comment').slideDown(); }); ...

Bump the version number and request a message for the commit

Recently diving into the world of Grunt, I've been experimenting with merging grunt-bump and grunt-prompt. My intention is to have users prompted for a commit message that will then be added to the commit. I looked to this article for guidance in str ...

Transfer a PHP variable between pages to retrieve the appropriate item from a button

In my project, I have two pages named content.php and pagecontent.php. In content.php, I am fetching product information from a database and displaying it in table format. The table has a grid layout with 2 rows and 3 columns. Each cell contains the descri ...

Steps for resolving the "endless redirection loop" issue in Sharepoint

I am currently learning Javascript and working on setting up a multi-language Sharepoint site. I am trying to implement a code into each page that checks the user's email and the language in the URL (Portuguese or Spanish) and then redirects according ...