js method to delete a field in an object

js method to delete a field in an object

This article mainly introduces the implementation of js to delete a field in an object, and shares it with you, as follows:

// The following method does not change the original object let item = {
    name:'Zhang San',
    age:'18',
    gender:'male'
   };
   console.log(item) // {age: "18",gender: "male",name: "Zhang San"}


   let { age,...params } = item;
   console.log(item) // {age: "18",gender: "male",name: "Zhang San"}
   console.log(typeof params.age) // undefined
   console.log(params) // {gender: "男",name: "张三"}

   // The following methods will directly change the object let item1 = {
    name:'Zhang San',
    age:'18',
    gender:'male'
   };
   console.log(item1) // {age: "18",gender: "male",name: "Zhang San"}
   delete item1.name;
   console.log(typeof item1.name) // undefined
   console.log(item1) // // {age: "18",gender: "male"}

Contrary to popular belief, the delete operator has nothing to do with directly freeing memory. Memory management is done indirectly by breaking references, see the Memory Management page for details.

The delete operator removes the specified property from an object. If the deletion is successful, it will return true, otherwise it will return false.

However, the following situations require important consideration:

If the property you are trying to delete does not exist, then delete will have no effect, but will still return true.
If there is a property on the prototype chain of the object with the same name as the property to be deleted, then after deleting the property, the object will use the property on the prototype chain (that is, the delete operation will only work on its own properties)
Any property declared with var cannot be deleted from the global scope or from the scope of a function.
In this case, the delete operation cannot delete any function in the global scope (regardless of whether the function comes from a function declaration or a function expression).
Except for functions in the global scope, which cannot be deleted, functions in objects can be deleted using the delete operation.
Any property declared with let or const cannot be deleted from the scope in which it is declared.
Non-configurable properties cannot be removed. This means that properties of built-in objects like Math, Array, Object and properties set to non-settable using the Object.defineProperty() method cannot be deleted.

The following code block gives a simple example:

var Employee = {
 age: 28,
 name: 'abc',
 designation: 'developer'
}

console.log(delete Employee.name); // returns true
console.log(delete Employee.age); // returns true

// When trying to delete a non-existent attribute // This will also return true
console.log(delete Employee.salary); // returns true

Non-configurable properties

When a property is set to be unsettable, the delete operation will have no effect and will return false. In strict mode a SyntaxError will be thrown.

var Employee = {};
Object.defineProperty(Employee, 'name', {configurable: false});

console.log(delete Employee.name); // returns false

Non-settable properties created by var, let, and const cannot be deleted by the delete operation.

var nameOther = 'XYZ';

// Get global properties through the following methods:
Object.getOwnPropertyDescriptor(window, 'nameOther');

// Output: Object {value: "XYZ",
// writable: true,
// enumerable: true,
// configurable: false}

// Because "nameOther" is added using the var keyword,
// It is set to non-configurable
delete nameOther; // return false

In strict mode, such an operation will throw an exception.

Strict mode vs. non-strict mode

In strict mode, if the delete operation is used on a direct reference to a variable, a function parameter, or a function name, a syntax error (SyntaxError) will be thrown. Therefore, to avoid syntax errors in strict mode, you must use the delete operator in the form delete object.property or delete object['property'].

Object.defineProperty(globalThis, 'variable1', { value: 10, configurable: true, });
Object.defineProperty(globalThis, 'variable2', { value: 10, configurable: false, });

console.log(delete variable1); // true

// SyntaxError in strict mode.
console.log(delete variable2); // false

function func(param) {
 // SyntaxError in strict mode.
 console.log(delete param); // false
}

// SyntaxError in strict mode.
console.log(delete func); // false

Any variable declared with var is marked as non-settable. In the following example, salary is not settable and cannot be deleted. In non-strict mode, the following delete operation will return false.

function Employee() {
 delete salary;
 var salary;
}

Employee();

Let's see how the same code behaves in strict mode. Will throw a SyntaxError instead of returning false.
"use strict";

function Employee() {
 delete salary; // SyntaxError
 var salary;
}

// Similarly, any direct use of the delete operator on any function // will throw a syntax error.

function DemoFunction() {
 //some code
}

delete DemoFunction; // SyntaxError

Example

// Create adminName attribute in global scope adminName = 'xyz';

// Create the empCount property in the global scope // Because we used var, it will be marked as non-configurable. Likewise let or const are not configurable.
var empCount = 43;

EmployeeDetails = {
 name: 'xyz',
 age: 5,
 designation: 'Developer'
};

// adminName is a property of the global scope.
// Because it is not created with var, it can be deleted.
// Therefore, it is configurable.
delete adminName; // returns true

// In contrast, empCount is not configurable.
// because var was used when creating it.
delete empCount; // returns false

// delete can be used to delete the attributes of an object delete EmployeeDetails.name; // returns true

// Even if the property does not exist, it will return "true"
delete EmployeeDetails.salary; // returns true

// delete has no effect on built-in static properties delete Math.PI; // returns false

// EmployeeDetails is a property of the global scope.
// Because it is defined without "var", it is marked as configurable.
delete EmployeeDetails; // returns true

function f() {
 var z = 44;

 // delete has no effect on local variable names delete z; // returns false
}

delete and prototype chain

In the following example, we delete an object's own property while a property with the same name is available on the prototype chain:

function Foo() {
 this.bar = 10;
}

Foo.prototype.bar = 42;

var foo = new Foo();

// Returns true because the property deleted is the foo object's own property delete foo.bar;

// foo.bar is still available because it is available on the prototype chain.
console.log(foo.bar); //42

// Delete the property from the prototype delete Foo.prototype.bar; //true

// Since the "bar" property has been removed, it can no longer be inherited from Foo.
console.log(foo.bar); //undefined

Deleting an array element

When you delete an array element, the length of the array is not affected. This is true even if you delete the last element of the array.

When an array element is deleted using the delete operator, the deleted element no longer belongs to the array. In the following example, delete is used to delete trees[3].

var trees = ["redwood","bay","cedar","oak","maple"];
delete trees[3];
if (3 in trees) {
  // This will not be executed}

If you want an array element to continue to exist but have a value of undefined, you can assign undefined to the element instead of using delete. In the following example, trees[3] is assigned the value undefined, but the element still exists.

var trees = ["redwood","bay","cedar","oak","maple"];
trees[3] = undefined;
if (3 in trees) {
  // This will be executed}

If you want to remove an array element by changing the array's contents, use the splice() method. In the following example, trees[3] is removed from the array by using splice().

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
trees.splice(3,1);
console.log(trees); // ["redwood", "bay", "cedar", "maple"]

This is the end of this article about deleting a field in an object with js. For more information about deleting a field in an object with js, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to delete a property of an object in JavaScript
  • Detailed explanation of the case of deleting a property in an object in JS
  • js deletes null, undefined, empty objects and empty arrays in objects/arrays
  • js delete usage (delete object properties and variables)
  • Detailed explanation of the properties and methods of dynamically adding, modifying, and deleting objects in javascript
  • JavaScript removes unnecessary properties of an object

<<:  jQuery realizes the full function of shopping cart

>>:  Summary of 11 amazing JavaScript code refactoring best practices

Recommend

About Generics of C++ TpeScript Series

Table of contents 1. Template 2. Generics 3. Gene...

Solve the matching problem in CSS

Problem Description As we all know, when writing ...

How to directly reference vue and element-ui in html

The code looks like this: <!DOCTYPE html> &...

MySQL SQL statement analysis and query optimization detailed explanation

How to obtain SQL statements with performance iss...

JavaScript regular verification password strength implementation method

exhibit design Password strength analysis The pas...

A brief analysis of how to upgrade PHP 5.4 to 5.6 in CentOS 7

1. Check the PHP version after entering the termi...

Docker FAQ

Docker only maps ports to IPv6 but not to IPv4 St...

Detailed introduction to deploying k8s cluster on centos7 system

Table of contents 1 Version and planning 1.1 Vers...

How to use Antd's Form component in React to implement form functions

1. Construction components 1. A form must contain...

MySQL multi-instance configuration application scenario

Table of contents MySQL multiple instances Multi-...

202 Free High Quality XHTML Templates (2)

Following the previous article 202 Free High-Qual...

Common causes and solutions for slow MySQL SQL statements

1. Slow query due to lack of index or invalid ind...

The difference between Display, Visibility, Opacity, rgba and z-index: -1 in CSS

We often need to control the hidden, transparent ...