0

I have a function that takes the full-path(a.b.c) to a field in an object and deletes it, i pass the object as a parameter, part of the function is reassigning the object parameter which is a reference to the object being modified, but when i log the object, nothing has changed except for that one field being deleted, I reassign it's reference inside the function but it stays the same outside, why?

    function deleteObjectKey(object, fieldPath) {
      const fields = fieldPath.split('.');
      for (let i = 0; i < fields.length; i += 1) {
        const field = fields[i];
        if (i === fields.length - 1) {
          delete object[field];
        }
        if (object[field] === undefined) {
          return;
        }
        object = object[field];
      }
    }

    const obj = { a: { b: { c: 'hello' } } };
    deleteObjectKey(obj, 'a.b.c');
    console.log(obj);
    // outputs: { a: { b: {} } }
  • 2
    That's because properties within the passed object will be changed, but the object won't be changed, if you try to change it directly in the function. [Here](https://stackoverflow.com/a/3638034/9038475) is an explanation for that exact behavior. – Geshode Jun 08 '23 at 05:41
  • Thanks, I read the referenced answer, I guess the re-assignment just creates another local variable with the same name. it's still weird to me though, I have been thinking of object reference strictly as memory address. – nitesh yadav Jun 09 '23 at 23:11

0 Answers0