JavaScript delete object attribute summary method

 1. Delete the attributes in the object in js

1. Use the delete operator

example:

1) Delete using the dot property accessor:

delete object.property;

When an operator is applied on a property accessor delete, the operator removes the corresponding property from the object:

const obj = {name: '十六个人博客',url: 'rwlok.com'};
delete obj.url;
console.log(obj); // { name: '十六个人博客' }

2) Use square bracket property accessors to delete:

delete object['property'];// orconst name = 'dynamicProperty';
delete object[name];

Removing a property using deletethe operator is mutable because it mutates the original object.

If the property name to be removed is determined dynamically, you can use the square bracket syntax:

const obj = {  name: '十六个人博客',  url: 'rwlok.com'};
const name = 'url';
delete obj[name];
console.log(obj); // { name: '十六个人博客' }

2. Use rest to deconstruct objects

1) The property name is known:

const { property, ...restObject } = object;

After applying destructuring and restsyntax, the same attributes restObjectas will be included object, just without the removed ones.

const obj= {
  name: '十六个人博客',
  url: 'rwlok.com'
};
const { url, ...objRest } = obj;
console.log(objRest); // { name: '十六个人博客' }
console.log(obj); // { name: '十六个人博客',url: 'rwlok.com' }

2) Property names are dynamic:

const name = 'property';
const { [name]: removedProperty, ...restObject } = object;

If the property names to be removed are determined dynamically, you can use the dynamic property name deconstruction syntax:

const obj = {  name: '十六个人博客',  url: 'rwlok.com'};
const name = 'url';
const { [name]: removedProperty, ...objRest } = obj;
console.log(objRest); // { name: '十六个人博客' }

The rest structure method can also delete multiple attributes at once:

const obj = {
  name: '十六个人博客',
  url: 'rwlok.com',
  title: '卡卡测速网', 
};
const { url, title, ...objRest } = obj;
console.log(objRest); // { name: '十六个人博客' }

Guess you like

Origin blog.csdn.net/weixin_44030860/article/details/128609173