0

I met some needs for deep copying original object literals, excepts some keys. I know spread operator doesn't copy deeply whole nested objects, however it's not main points for this question, so let's pass that issues.

so, back in original question, I see no difference between using delete keyword and assign undefined to target property which I want to remove.

const original = {
   a: 1,
   b: 2,
}

const copied = {
  ...original,
  b: undefined
}

const explicitDelete = {
 ...original
}
delete explicitDelete["b"]

seems copied way is less verbose, but it's totally okay with that way?

1
  • 1
    copied.hasOwnProperty('b') vs. explicitDelete.hasOwnProperty('b') Commented Apr 28, 2022 at 2:46

5 Answers 5

3

I see no difference between using delete keyword and assign undefined to target property

The difference is that the property still exists with the value undefined:

"b" in copied // true
"b" in explicitDelete // false

If you don't like the verbosity of delete, you can use a helper function

function omit(obj, ...keys) {
  const res = {};
  for (const p in obj)
    if (!key.includes(p))
      res[p] = obj[p];
  return res;
}
omit(orignal, "b")

or object destructuring with rest syntax:

const {b:_, ...withoutB} = original;

See also How to omit specific properties from an object in JavaScript, How do I remove a property from a JavaScript object?, How can I clone a JavaScript object except for one key?.

Sign up to request clarification or add additional context in comments.

Comments

0

There is definitely a difference. When you use delete, the object will no longer have the property name at all. The in operator will indicate that. Setting the property value to undefined will not have that effect.

Comments

0

delete removes the entry, that's the difference

enter image description here

Comments

0

let original = {a: 1, b: 2}
console.log("Original object:")
console.log(original)
original["a"] = undefined
console.log("After setting to undefined:")
console.log(original)
delete original["a"]
console.log("After actually deleting:")
console.log(original)

delete actually removes the key from the object, but setting it to undefined leaves the key, and just makes the key undefined. The difference is subtle, but it can become important in some cases.

Comments

0

It is a difference. with delta your will remove the key "b" completely from the object. However, when you assign undefined the key still be there and having undefined assigned.

enter image description here

1 Comment

Please post actual code here using the code formatting tools, and not an image of code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.