Joe Packer
Joe Packer

Reputation: 525

Remove element from javascript Object

I need to keep the overall layout of an object. I pass it into a method and:

  1. I need to delete things from the object, then do something,
  2. once I get back to the main function I was in
  3. I need the object to be UNTOUCHED.

The way it is setup now it deletes it from the main object as well as the one in the bottom method. SEE JSFiddle for code http://jsfiddle.net/rwux4rta/ To get the results from the run, see console

Please HELP!

$( document ).ready(function() {
    var pList = new Object();
    pList["test"] = "test"; //this is being deleted from BOTH instances of the Obj
    pList["test1"] = "test1";
    pList["test2"] = "test2";
    pList["test3"] = "test3";
    pList["test4"] = "test4";

    displayData(pList);

    console.log(pList);
});

function displayData(badData){
    badData.test.removeData();

    console.log(badData);
}

Upvotes: 1

Views: 106

Answers (3)

guest271314
guest271314

Reputation: 1

Try

 $(document).ready(function() {
    var pList = new Object();
    pList["test"] = "test"; //this is being deleted from BOTH instances of the Obj
    pList["test1"] = "test1";
    pList["test2"] = "test2";
    pList["test3"] = "test3";
    pList["test4"] = "test4";
    // extend `pList` to `_pList` object
    var _pList = $.extend({}, pList);
    displayData(_pList);

    console.log(pList, "original");
});

function displayData(badData){
    delete badData.test;

    console.log(badData, "extended");
}

jsfiddle http://jsfiddle.net/guest271314/rwux4rta/6/

Upvotes: 1

marty
marty

Reputation: 484

You can clone the object before you delete the "bad" data. I used the following function to clone an object based on advice found here https://stackoverflow.com/a/728694/1143670.

function clone(obj) {
    if (null == obj || "object" != typeof obj) return obj;
    var copy = obj.constructor();
    for (var attr in obj) {
        if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
    }
    return copy;
}

You will want to update your displayData function so that it clones the data coming in the "badData" parameter.

function displayData(badData){
   var newBadData = clone(badData);

   delete newBadData.test;

   console.log(newBadData);
}

The rest should remain the same and this was only tested in chrome. See this fiddle for a working example.

Upvotes: 1

Ryan
Ryan

Reputation: 415

In other words, your question is asking how to pass JavaScript objects by value, not by reference. By default, JavaScript passes all objects by reference, so as you've noticed, any modification to that object in a function will impact the original object as well.

Check out this thread to see how you can accomplish a pass by value:

JavaScript: How to pass object by value?

Upvotes: 1

Related Questions