0

I have users defined as such;

const initUsers = {
  'a@test.com':{
    firstName: 'A',
    lastName: 'Test',
    email: 'a@test.com',
    password: 'test',
  },
  'b@test.com':{
    firstName: 'B',
    lastName: 'Test',
    email: 'b@test.com',
    password: 'test',
  }
};

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

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['a@test.com']

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 `a@test.com`, and if you want to change it to `b@test.com`, you **can't** update it in place, you have to add a new object keyed under `b@test.com` manually, then delete the `a@test.com`, 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