I have a JavaScript object as follows.
var sampleData = {
"studentsList": {
"Student1": {
"marks": "123",
"grade": "B"
},
"Student2": {
"marks": "144",
"grade": "A"
}
}
};
Now the user enters the name of a student, say Student1 and I need to get the details of that object.
I have two questions.
[1] How do I get the details of the entered student using JavaScript?
When I use sampleData.studendsList.valueOf("Student1") returns me the complete object. I just need the details of “Student1”.
[2] Is this the correct way to do it? Or we should create an array of Students and that contains an property called “name” with value say Student1 ? If I go with this approach then I need to iterate through the entire array list to get the details of a student.
Which appraoch is better?
An array is usually the more natural way to store a list of items (like students). But there are tradeoffs. As structured (using objects), you can access any student by name in constant time:
Structuring with an array looks like this:
Access the
nthstudent like this:If the index of the desired student is not known, then accessing a particular student (based on its details) is
O(n)(because you’d need to iterate the entire array to find the correct item in the worst case).