When you delete a property from a duplicated version of an Object in JavaScript, it ends up impacting the original Object as

Let's imagine we have an array of objects,

var data = [{
    "sss": "sssssss",
    "yyy": "ssdsdsds",
    "www": "1212121",
    "Group": "Mango"
}, {
    "sss": "sssssss",
    "yyy": "ssdsdsds",
    "www": "1212121",
    "Group": "Mango"
}]

The desired final result is:

var newData ={
   "Mango" : [
        {
            "sss": "sssssss",
            "yyy": "ssdsdsds",
            "www": "1212121"
        }, {
            "sss": "sssssss",
            "yyy": "ssdsdsds",
            "www": "1212121"
        }
    ]
}

To achieve this, the following approach was taken:

var newObj = [];

for(var i = 0; i < data.length; i++ ){
    if(newObj[data[i].Group] && newObj[data[i].Group].constructor === Array ){

    }else{
        newObj[data[i].Group] = [];
        // ################### PROBLEM ==========
        var temp = data[i];
        delete temp.Group;
        console.log(data[i]);
        // ################### ==================
        newObj[data[i].Group].push(data[i]); // error: data[i].Group is undefined 
    }
}

In this code snippet, the intention was to remove the property "Group" from variable "temp" However, it seems like the console.log(data[i]); displays that the property "Group" has been removed from data[i] (which is the original). How is this possible?

It appears that the variable temp is referencing the original data[i], but this is uncertain. How does deleting a property from a copied object affect the original one? How can this issue be resolved?

Answer №1

To efficiently manage objects and properties, utilize a hash structure along with the delete operator to eliminate specific property values.

var data = [{
    "name": "John Doe",
    "age": 30,
    "city": "New York",
    "occupation": "Developer"
}, {
    "name": "Jane Smith",
    "age": 25,
    "city": "Los Angeles",
    "occupation": "Designer"
}]

var groupByField = function(collection, field) {
  return collection.reduce(function(result, item) {
    (result[item[field]] = result[item[field]] || []).push(item);
    delete item[field];
    return result;
  }, {});
};
console.log(groupByField(data, 'city'));

Furthermore,

What is the impact of removing a property from the cloned object on the original one?

To prevent unintended consequences, implement a deep clone for that particular object.

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

The some() method in Javascript with an extra argument

I want to validate if at least one element in an array satisfies a certain condition. The condition is based on a variable. Here's an example of how I'm currently attempting this: function checkCondition(previousValue, index, array) { retur ...

Issue with Microsoft Azure and AngularJS: Chart not rendering data as expected

I've encountered an issue where I can view the data locally, but once I open the Windows Azure cloud service application, the Json data is no longer being passed into my chart (). The Console displays a message stating "Controller names should start w ...

Patience is key when using Selenium with Node.js - make sure to wait for the

Is there a way to ensure my code waits until the page is fully loaded in Node.js while using selenium-webdriver version 4.0.0? const driver = new Builder().forBrowser("firefox").build(); await driver.get("http://www.tsetmc.com/Loader.a ...

Select2 loading screen featuring preloaded value

Trying to populate a select2 box with instrument options on an edit profile page for a musician site. The information is pulled from the database, but I'm struggling to display the existing instrument list in the select2 box upon render - it always ap ...

Prevent the movement of the first column in a table when rearranging rows up or down by utilizing

Feeling a bit stuck here, can't seem to figure out what I've missed. I've managed to move up or down a row in a table, but I need the value of the cell in the first column to remain unchanged. Here's my code: This is my HTML file: &l ...

reloading a URL dynamically using an array in JavaScript

I need assistance with a Chrome extension code. The goal is to have it check the page that initially loads, and if it matches my website st.mywebsite.com, execute the specified code. Currently, it does not perform this check and runs on every loaded page ...

An element featuring a background color is vertically aligned in the middle of its parent container

Struggling to achieve a seemingly simple task, but coming up short on finding a solution. The goal is to have a background-color that aligns vertically in the middle of the first and last images in a stack of images. It may sound more complicated than it a ...

Implementing automatic token refreshing and automatic logout features in Vue

I am a novice web developer looking to enhance my skills. For my initial project, I decided to incorporate Laravel and Vue. My main objectives are to: Implement an auto-logout feature after 3 minutes of user inactivity Create an automatic ping to my token ...

Identifying the color category based on the color code in the props and displaying JSX output

I am in need of a solution to display colors in a table cell. The color codes are stored in mongodb along with their descriptions. I am looking for a library that can determine whether the color code provided is in RGB or hex format, and then render it acc ...

jQuery UI Slider is malfunctioning (code example included)

I've implemented a jQuery UI slider on my website, and it's functioning quite well. You can check out the slider HERE. However, I've noticed that when I click on 'back to the top', the page smoothly scrolls up. But when I use the ...

Guide on utilizing nested arrays in Gatsby using ReactJS and GraphQL

One of my components, menu.js, is imported into a page to display a list of articles that can be filtered by category, and it works as expected. Now, I want to modify the component so that I can filter the articles by tags. The issue is that the tags are ...

Opt for CSS (or JavaScript) over SMIL for better styling and animation control

I recently noticed an alert in my Chrome console that SVG's SMIL animations are being deprecated and will soon be removed. The message suggested using CSS or Web animations instead. Since I want to transition from SMIL to CSS animations, there are a ...

How to prevent the parent element from scrolling when changing the value of a number input by scrolling

Within a container with fixed dimensions and scroll bars that appear when the content size exceeds the container, there is a form. This form contains an input of type "number" which allows changing its value using the mouse wheel. The issue arises when at ...

The error message "[Insecure URL]" was triggered at line 85 of angular.min.js in the AngularJS framework

Looking for some assistance with Angular as I have limited knowledge. It was working fine on localhost, but after upgrading from PHP5 to PHP7, I encountered this error: angular.min.js:85 Error: [$sce:insecurl] http://errors.angularjs.org/1.2.13/$sce/inse ...

displaying a PDF file in Safari

Is there a way to display a PDF document within an HTML page without encountering a missing plugin error? I attempted to use the following code, but the error persists. Interestingly, if I drag the same PDF file directly into my browser, it displays perfe ...

Storing Django models in a JSON dictionary for multiple entries

How can I generate a json output containing a dictionary with multiple models in the following format: results = {} results["game_info_db"] = db.gameInfo.objects.get(name='name') results["dlc_list_db"] = db.gameAddon.objects.filter(game__name=& ...

Struggling to align the Title Tags perfectly in the center of Images

When attempting to center align images and their post titles, I encountered an issue where the left part of the image and title were being cut off by a small margin. Despite trying various methods, I was unable to successfully center the title tags. You ca ...

How to retrieve the image source from a block using jQuery

Currently, I am working on developing a slider for my webpage using jquery's "Cycle" plugin. However, I have encountered an issue with accessing the image sources used in the slider. To provide more context, here is a snippet of code from the 'he ...

Tips for concealing the final click (add) tab after it has been clicked and revealing the hidden (add) button when the user clicks on the remove button

I have created a form where users can add tests. Everything is working smoothly but I want the previous "Add Another Test" field to be removed when the user clicks on it and a new field to be shown. Everything is running well, but the issue is that when t ...

Removing a single object from an array of objects using MongooseJS

Hello to all the MongooseJS experts out there! I'm a newcomer to MongooseJS, and I've been trying to solve this problem for the past two days but haven't found a solution yet. Thank you in advance for any help! The Issue with My Delete me ...