0

I'm new to JavaScript and I want a Data Structure for my JavaScript code which stores Student data as key value pairs. The key is the student Registration number and the value is the students name.What I'm thinking is to create a JavaScript object as follows and store data as follows

let Student={
    001A:"John",
    002A:"Mathew"
};

Is this approach is correct? And if it is correct suppose a way to dynamically add key value pairs to that. Thank you

BenSV
  • 139
  • 4
  • 13

2 Answers2

0

That would be an object literal. You'd want the key to be a string, but other than that you've basically got it. You can dynamically add properties using bracket syntax. I've attached a small snippet to give you an idea of how it works. :)

let Student={
    "001A":"John",
    "002A":"Mathew"
};

Student["003A"] = 'Jessica';

Object.entries(Student).forEach(entry => console.log(entry) );
Joel Hager
  • 2,990
  • 3
  • 15
  • 44
0

The approach is correct. Given

const students={
    '001A': 'John',
    '002A': 'Mathew',
};

(Note: It's a good idea to keep your key as a string to prevent collisions with reserved keywords) To read from the structure you can access the given record via

console.log(students['001A']); // => 'John'

To add new records dynamically, you just add a new property and assign it the desired value:

students['007'] = 'Ben';

which results in

console.log(students);
// =>
{
  '001A': 'John',
  '002A': 'Mathew',
  '007': 'Ben',
};

To delete a given record you can do either

delete students['007'];

or

students['007'] = undefined;

The first option is a little "cleaner" as it completely deletes the given key, along with its assigned data. Keep in mind that the data will be removed once you reload the page.

Philipp Meissner
  • 5,273
  • 5
  • 34
  • 59