1

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?

Community
  • 1
  • 1
  • You are trying to read `populationData` and not `studentsData`? – David S. Nov 10 '16 at 03:16
  • You need to clarify what language you are writing in. and add that in the tag as well. – GeneCode Nov 10 '16 at 03:17
  • You have missed something. What is `populationData` in the first and second case? Since it works in case #1, show where and how declare it. – Yeldar Kurmangaliyev Nov 10 '16 at 03:17
  • You've tagged your post "local-storage", but do not mention local storage. Does this question have something to do with local storage? Does it have something to do with JSON? –  Nov 10 '16 at 15:58

3 Answers3

0

You are accessing wrong variable. use studentsData instead:

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);  
Sachin Gupta
  • 7,805
  • 4
  • 30
  • 45
0

console.log(studentsData[0].studentName);

Since you are adding the json object to studentsData array.

0

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);
Debug Diva
  • 26,058
  • 13
  • 70
  • 123