Reputation: 49
var test=[];
$(document).ready(function(){
$.getJSON("data.json",function(data){
$.each(data,function(key,value){
test.push(value.topic);
});
});
});
Here is my javacript code. I want to push json object's all values with key as topic. But when I try to access test[i] (i be any integer within array length) I get an error "undefined" . What' am I msissing?
Here is my json object sample-
[
{
"topic": "Books",
"quantity": 3
},
{
"topic": "Grossery",
"quantity": 3
},
{
"topic": "stationery",
"quantity": 3
},
{
"topic": "food",
"quantity": 2
},
{
"topic": "market items",
"quantity": 3
}
]
Upvotes: 0
Views: 92
Reputation: 588
Your code seems to be working fine for me.
Are you accessing the data before the callback that you pass to getJson
has been executed?
Here's an example that works if I serve it locally using python3 -m http.server 8080
:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
var test=[];
$(document).ready(function(){
$.getJSON("data.json",function(data){
$.each(data,function(key,value){
test.push(value.topic);
});
// only use test array after data has been loaded
doWork();
});
});
function doWork() {
$('#output').text(
test + ' ' + test[0]
);
}
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>
Upvotes: 0
Reputation: 5162
See the following working code:
var data = [
{
"topic": "Books",
"quantity": 3
},
{
"topic": "Grossery",
"quantity": 3
},
{
"topic": "stationery",
"quantity": 3
},
{
"topic": "food",
"quantity": 2
},
{
"topic": "market items",
"quantity": 3
}
]
var test = [];
$.each(data,(i,v) => test.push(v.topic));
console.log(test);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
Upvotes: 1