What is the difference between these 2 ways of creating a list of arrays in JavaScript?


What is the difference between these 2 ways of creating a list of arrays in JavaScript?



How do I dynamically create a list of arrays in JavaScript, that actually shows up in the Developer console as a list of arrays?



Just rephrased this question; there are plenty of examples how to do this, and my code is working, but I'm getting 2 very different results from these 2 methods:



I tried this:


var volume = ;
for (i = 0; i < json.length; i++) {
var item = new Array(2);
item[0] = json[i].json_date;
item[1] = json[i].volume;
volume.push(item);
}



So, this code works, and seems to create an array of arrays, but in the developer console the result of console.log(typeof volume[0]) is undefined.



If I create the array manually, it works much better:


var volume = [
[1313964000000,23.17],
[1314050400000,23.78],
[1314741600000,25.24],
[1314828000000,24.77],
[1440021600000,82.69]
];



Now console.log(typeof volume[0]) is object. And console.log(volume) results in: (5) [Array(2), Array(2), Array(2), Array(2), Array(2)]. That's what I need, not just .



I've spent the entire day searching for answers, and have tried many variations of this code, but can't seem to find code that will dynamically create that volume array to correctly show up as an array of arrays.



Has anyone else run into this?



Here is the full code:


var volume = ;

fetch("http://localhost:3000/api/v1/TSLA").then(function(response) {
if(response.ok) {
response.json().then(function(json) {
for (i = 0; i < Object.keys(json).length; i++){
volume.push(new Array(json[i].json_date, json[i].volume));
}

});
} else {
console.log('Network request failed with response ' +
response.status + ': ' + response.statusText);
}
});

console.log(volume);



So, the answer from oknawe helped me to solve this problem; however in a way the question has still not been answered, because the volume array is only usable inside that fetch function. Later in the code, the data is still there, but individual elements test as undefined...





Your code should work fine. You're probably doing something else wrong (eg, not waiting for async).
– SLaks
Jun 28 at 22:44





What does the variable json look like? How are you getting that? (Try dumping that to the console.)
– Ashton Wiersdorf
Jun 28 at 22:47


json





The json part is fine: {signal_date: "2010-06-29T04:00:00.000Z", json_date: 1277769600000, open: 19, high: 25, low: 17.54, …} - just a bunch of records like that.
– Russ Karlberg
Jun 28 at 23:38





And yes, the code does work... but the type of arrays inside the main array is undefined for some reason, and no matter what I try, I can't get those inside arrays to show up as Array(2)
– Russ Karlberg
Jun 28 at 23:39





@RussKarlberg see my answer below. The loop will never get iterated over since json.length will be undefined
– joknawe
2 days ago


json.length


undefined




3 Answers
3



The length of a JSON object will be undefined since objects do not have a length value. You can use Object.keys to get size but that won't do you much good since object values cannot be accessed by index:


length


undefined


length


Object.keys


var volume = ;
for (i = 0; i < Object.keys(json).length; i++) {
// can't access using json[i] here
}



However, you can use Object.keys(json) or Object.values(json)
and do something like below:
(you'll need to have code inside the json callback)


Object.keys(json)


Object.values(json)


let volume = ;
fetch('/api/foo/bar').then((data) => {
return data.json();
}).then((json) => {
console.log(json);
Object.keys(json).forEach((obj) => {
// obj = {"json_date": 1313964000000, "volume": 23.17, ...}
console.log(obj);
volume.push(new Array(obj["json_date"], obj["volume"]));
});
console.log(volume);
}).catch((e) => {
console.error('There was a problem with the request');
})





@RussKarlberg - updated code above should help you fix the issue.
– joknawe
2 days ago






this code assumes the response is indeed an object not an array of objects
– joknawe
2 days ago






@RussKarlberg - sorry, just made one final update
– joknawe
2 days ago





Ok, I made these updates to my code, the good news is that it's giving me the list of arrays that I need... but the elements of the array are all undefined...
– Russ Karlberg
2 days ago





Finally got it working - using volume.push(new Array(json[obj].json_date, json[obj].volume));
– Russ Karlberg
2 days ago



That should work fine, assuming the variable json is structured as you expect. You can also try:


json



let volume = json.map((i) => [i.json_date, i.volume]);


let volume = json.map((i) => [i.json_date, i.volume]);



(Provided your environment lets you use ES6.)



Instead of manually looping over the array, you can iterate over the contents of the array with the map function.


map





Thanks for the help. I tried that, and the code is certainly more succinct. I am using the latest version of everything. The json data is coming from an API, and that parts works fine. But I need to create this array of arrays for loading into HighCharts, and that part is simply not working, with no errors or warnings.
– Russ Karlberg
Jun 28 at 23:31



Thanks to oknawe, I got it working. Using that code works, provided I use that volume array inside the fetch code. Outside that, the volume array still contains data, but individual elements are undefined. Many thanks to everyone who posted here!






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Export result set on Dbeaver to CSV

Opening a url is failing in Swift