0

I have users defined as such;

const initUsers = {
  '[email protected]':{
    firstName: 'A',
    lastName: 'Test',
    email: '[email protected]',
    password: 'test',
  },
  '[email protected]':{
    firstName: 'B',
    lastName: 'Test',
    email: '[email protected]',
    password: 'test',
  }
};

I am able to retrieve a user by doing initUser['[email protected]']. How do I delete the users based on their key which is the email like [email protected]? Or how do I replace it with another key, for example, [email protected] in place of [email protected]?

Thank you. (JavaScript Beginner)

MNS
  • 3
  • 1
  • 1
    Thanks @Cauterite. I came across similar links, but I didn't realise objects within objects could be accessed similarly. Now I see it could be a possible duplicate. – MNS May 29 '17 at 23:18

1 Answers1

0

Use Javascript delete keyword to delete objects' properties

delete initUsers['[email protected]']

Should delete it for you

You can't change a property's name of an object. Best bet is to add the new property to the object and delete the one you want to replace

Trash Can
  • 6,608
  • 5
  • 24
  • 38
  • Thanks, it worked like a charm. I will accept the answer after my timer. Another quick question: I am providing the option to update user info. Would it be better to delete the old object and replace with a new object containing the new data (as email/key may have been updated) or delete properties and re-add them? – MNS May 29 '17 at 23:10
  • Like I said, if your object is keyed under `[email protected]`, and if you want to change it to `[email protected]`, you **can't** update it in place, you have to add a new object keyed under `[email protected]` manually, then delete the `[email protected]`, but if they key did not change, only the object which it maps to did, you don't need to delete the key, if you add a new key with a same name to one of the current keys, then that key's value will just be overwritten with the new value – Trash Can May 30 '17 at 01:17