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
}
]
puranjay11mpuranjay11m
2 Answers 2
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>
answered May 2, 2018 at 12:18
3 Comments
puranjay11m
I want to fetch the json data instead of creating a json object in javascript file
puranjay11m
Your code seems that you have created an object and copied the values itself
Md Johirul Islam
I am assuming you got correct data that you showed from your
$.getJSON()
callYour 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>
2 Comments
puranjay11m
Did you try to access the test array just before the script tag ends?
ambiso
No, the access happens inside the callback passed to
getJSON
. You can sequence your actions after the callback by wrapping them in a function and calling that function from the callback. I'll edit the answer.lang-js
undefined
data key value and test
at each call to function. You will understand what is the problem.