Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu April 18, 2023 › #HowTo #Javascript

How to remove property from object in JavaScript without delete

There are various ways to remove a property from an object in JavaScript. One option is to use the delete operator, like so.

delete myObject.RGB;

However, this mutates the original object, which may not always be desirable.

Remove property from JavaScript object without delete #

Another option, which doesn't mutate the original object, is to use object destructuring to create a new object with the desired properties.

const {propToRemove, ...newObject} = myObject;

This creates a new object called newObject that contains all the properties of myObject except for propToRemove.

<script>
 let myObject = {
  "name": "Red",
  "Hex": "#ff0000",
  "RGB": "rgb(255,0,0)"
};

 const {RGB, ...newObject} = myObject;

 console.log(myObject)
 console.log(newObject);
</script>

Remove property from object without delete using Object.assign() #

Use the Object.assign() method to create a copy of the object without the property.

<script>
 let myObject = {
  "name": "Red",
  "Hex": "#ff0000",
  "RGB": "rgb(255,0,0)"
};

 const copy = Object.assign({}, myObject);
 delete copy.RGB;

 console.log(myObject)
 console.log(copy);
</script>

In the above example, we use the Object.assign() method to create a new object called copy that is a copy of myObject. Then, we use the delete operator to remove the RGB property from copy.

Remove property from object without delete Using JSON.parse() #

Use the JSON.parse() and JSON.stringify() methods to create a copy of the object without the property.

<script>
 let myObject = {
  "name": "Red",
  "Hex": "#ff0000",
  "RGB": "rgb(255,0,0)"
};

 let copy = JSON.parse(JSON.stringify(myObject));
 delete copy.RGB;

 console.log(myObject)
 console.log(copy);
</script>

In the above example, we use the JSON.parse() and JSON.stringify() methods to create a new object called copy that is a copy of myObject. Then, we use the delete operator to remove the RGB property from copy.

save
listen
AI Answer
Write Your Answer
loading
back
View All