user3403964 user3403964 - 13 days ago 6
Javascript Question

adding JSON object to JSON array at runtime issue

simply I want to get value of a key at JSON object but at run time,
this work at design time like this.

var studentsData = [
{ "studentName": "Elen", "Birthyear": 1981 }
, { "studentName": "Stev", "Birthyear": 1987 }];
console.log(studentsData[0].studentName); // print Elen


But if push object to the array at runtime like this

var studentsData = [];
var jsonObj={ "studentName": "Elen", "Birthyear": 1981 }; //because i intend to get the object data at runtime
studentsData.push(jsonObj);
console.log(studentsData[0].studentName);


by this way it give me error :Uncaught TypeError: Cannot read property 'studentName' of undefined

please help, THANK YOU

Sorry by mistake i put different array variable from another code,
but it seems that My real problem from the start was the same non solved this problem :-
How do I assign a variable from localForage as I do in localStorage?

Answer

try to read studentsData instead of populationData.

working demo :

using for in loop :

 var studentsData = [
            { "studentName": "Elen", "Birthyear": 1981 }
            , { "studentName": "Stev", "Birthyear": 1987 }];

for (var i in studentsData) {
  console.log(studentsData[i].studentName);
}

using Array map() function :

 var studentsData = [
            { "studentName": "Elen", "Birthyear": 1981 }
            , { "studentName": "Stev", "Birthyear": 1987 }];

var result = studentsData.map(function(elem) {
  return elem.studentName;
});

console.log(result);