iterate though JSON array in p5.js [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 days ago.
Improve this question
I have a server that returns :
I want to iterate through this data in p5.js
var ms = []
function preload() {
var url ='https://dest/url'
ms = loadJSON(url)
}
Which I expected to return an array but it does not seem to return anything sensible.
However, if I paste the same data into the Javascript console I get different data :
How do I either iterate over this data (it is NOT loaded as an array) or convert it to an array?

I think you mean this:
var array;
for (var key in ms) {
if (!array) {
array = [a[key]];
} else {
array.push(a[key]);
}
}
console.log(array); // [ {'time': .... }, {...}, .. ]

You are getting an array of objects, Here's how you can simply iterate them
var data = [{"time":"12345","rate":"12345.12"}, {"time":"12345","rate":"12345.12"}, {"time":"12345","rate":"12345.12"}, {"time":"12345","rate":"12345.12"}, {"time":"12345","rate":"12345.12"} ];
for(obj of data){
console.log("time and rate: ", obj.time, obj.rate)
}

jettpleyn had the only answer that actually worked in P5.
Eventually though - it dawned on me that I could make my life easier by changing the JSON returned from the server to an object containing an array rather than an array directly
{ "data":
[{"time":"85579.54189181328","rate":177.66287},{"time":"81978.61475682259","rate":177.66287},{"time":"78377.54175782204","rate":177.66287},{"time":"74776.58741879463","rate":177.66287},{"time":"71175.57481980324","rate":177.66287},{"time":"67574.59330582619","rate":177.66287},{"time":"63973.427922964096","rate":177.66287},{"time":"60372.39295697212","rate":177.66287},{"time":"56771.37366294861","rate":177.66287},{"time":"53170.276379823685","rate":177.66287},{"time":"49569.180530786514","rate":177.66287},{"time":"45968.02240085602","rate":177.66287},{"time":"42365.825628995895","rate":177.66287},{"time":"38764.64792180061","rate":177.71416},{"time":"35163.241872787476","rate":177.71416},{"time":"31562.00651884079","rate":177.72556},{"time":"27960.898827791214","rate":177.73126},{"time":"24359.687824964523","rate":177.67998},{"time":"20758.03328180313","rate":177.67998},{"time":"17156.808887004852","rate":174.53839},{"time":"13555.605601787567","rate":174.9276},{"time":"9954.546007871628","rate":175.35431},{"time":"6353.40945982933","rate":175.96582},{"time":"2752.3464789390564","rate":175.84541}]
}

As others have pointed out in the comments, what you have is essentially an array or an array-like object to be more precise and these can easily be converted to a proper array like so:
ms.length = Object.keys(ms).length;
var msArray = Array.prototype.slice.call(ms);

Looing at an issue in the p5.js github about this problem, more than one person suggest to do Object.values(ms) to transform the object into an array.
It has to be done after the preload function.

Related

Why JSON.stringify() don't work correctly [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I'm actually creating a JSON file with nodejs but when i use the JSON.stringify.
My Json Object work correctly when i print it :
My code
But when i stringify my json object i get that :
What i receive when i print my json object
A big part of my json information don't want to be save i don't know why
Here's the code :
What i receive when i print my stringified json object
You are attempting to use a 'sparse array' to store your data. Arrays do not have a clear way to be instantiated with elements at a specified index.
An object (or a Map) would suit your requirements better. To use an object, I modified your 'accounts' initation code that was commented:
// replace this:
dataObj["accounts"] = [];
// with this:
dataObj["accounts"] = {};
The other code you are using (e.g. accessing elements using the square brackets) will work the same. You should probably make the same adjustments to the other arrays you are using.
Sparse arrays can get ugly in some notations if you have large blank spaces (which your UUID methodology would certainly have). An object or a Map will not suffer that shortcoming.
An example of similar code, using objects instead of arrays:
let dataObj = {};
dataObj["accounts"] = {};
let uuid = 'abcdefghij12344';
dataObj["accounts"][uuid] = {}
dataObj["accounts"][uuid]['active'] = true;
dataObj["accounts"][uuid]['someotherval'] = true;
console.log(dataObj);
//outputs:
{ accounts: { abcdefghij12344: { active: true, someotherval: true } } }
let stringified = JSON.stringify(dataObj);
console.log(stringified);
// Outputs:
{"accounts":{"abcdefghij12344":{"active":true,"someotherval":true}}}
let parsed = JSON.parse(stringified);
console.log(parsed);
//Outputs:
{ accounts: { abcdefghij12344: { active: true, someotherval: true } } }

value extraction from array in javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
business=[0:{"name":{"en":'prateek'}},1:{"name":{"ar":'rahul'}}]
How I can extract the value of en and ar from this type of the repeted object in a array
The issue with your question is that you define business as an Array with the use of square brackets, but then proceed to use key value pairs directly within the array (via the usage ":"), which is reserved for objects and not arrays. I'd recommend researching both array and object datatypes, however simply put:
let myArray = [1, 2, 3, ...];
// only stores values which can be retrieved using the values index i.e. myArray[0]
let myObj = {"key1" : "value1", "key2" : "value2"};
// values are stored against keys, and can be accessed via the key i.e. myObj.key1
I think you've confused how objects and arrays should work. My guess is that you'd be better off with this structure:
let businesses = [];
businesses.push({enName: 'prateek', arName: 'rahul'});
console.log(businesses[0], businesses[0].enName, businesses[0].arName);
This way you're using an array to hold a collection of businesses and which are represented by objects. These objects in turn have attributes for enName and arName.
I think this would be a much clearer way of structuring your issue.

iterate over formatted JSON Array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am querying an MS SQL Database, which is returning a formatted JSON Array. Below is an example of what is returned. I have used just about every JavaScript example I can find to iterate over the array, but nothing is working:
[
[
{"id":1,"Title":"Friday"},
{"id":2,"Title":"Saturday"},
{"id":3,"Title":"Sunday"}
]
]
There are two issues with your json array there that will need to be solved first
You have a " missing on Sunday
You have an array of arrays, not just an array.
When your array is correct the return from your SQL should look like this:
'[{"id":1,"Title":"Friday"},{"id":2,"Title":"Saturday"},{"id":3,"Title":"Sunday"}]'
That isn't a json object yet, it's just a string that looks like one, to make use of that as a json object/array you need to parse it like this:
var jsonArray = JSON.parse('[{"id":1,"Title":"Friday"},{"id":2,"Title":"Saturday"},{"id":3,"Title":"Sunday"}]');
If you can't get around the [[]] array within an array, you can handle it like this:
var jsonOuterArray = JSON.parse('[[{"id":1,"Title":"Friday"},{"id":2,"Title":"Saturday"},{"id":3,"Title":"Sunday"}]]');
var jsonArray = jsonOuterArray[0];
With that there are many ways to iterate over it in javascript, it all depends what libraries you use and what you want to get out of it, like how the jQuery example give not only the object but the position in the array for that object but the forEach will not.
For each example, jsonArray will be the parsed out json from your SQL, key will be the position in the array and value will be the object in the array.
JavaScript: (array prototype forEach)
jsonArray.forEach(function(value){
console.log(value.id, value.Title)
});
JavaScript: (for loop)
for (var key = 0; key < jsonArray.length; key++) {
var value = jsonArray[key];
console.log(value.id, value.Title)
};
jQuery:
$.each(jsonArray, function (key, value){
console.log(value.id, value.Title)
});
Using nodejs (ES5 syntax) :
> [[{"id":1,"Title":"Friday"},{"id":2,"Title":"Saturday"}, {"id":3,"Title":"Sunday"}]][0]
.forEach(function(elt){ console.log(elt.id, elt.Title)})
1 'Friday'
2 'Saturday'
3 'Sunday'
Note that a quote is missing before Sunday:
[[{"id":1,"Title":"Friday"},{"id":2,"Title":"Saturday"}, {"id":3,"Title":Sunday"}]]
therefore you will not be able to evaluate this JSON. Assuming that the JSON is corrected to
[[{"id":1,"Title":"Friday"},{"id":2,"Title":"Saturday"}, {"id":3,"Title":"Sunday"}]]
you will be able to iterate it in conventional manners, using a for cycle, for example.

Checking if an array contains a value? (I've tried some techniques but I'm still a bit lost) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am a beginner at JavaScript (beginner as in studying for about a week) and I'm stuck on how I can check if an array contains a certain string. Here I've made a word-guessing game.
I declare the function 'contains' like this:
function contains(thing, array){
if(thing in array){
return true;
}
else {
return false;
}
};
I'm not sure what I'm doing wrong, but the value is always false.
The function uses the third technique here. But I've also tried using the accepted technique here, both with the same result.
Any help is greatly appreciated!
Had to make a separate answer to make sure this is clear. The correct approach to see if something is in an array:
var myArr = ['apples', 'bananas', 'pears'];
if (myArr.indexOf('pears') > -1) { // myArr.indexOf('pears') will equal the number 2
console.log('we got pears'); // this will log
}
if (myArr.indexOf('hotdogs') > -1) { // since it's not in the array, it's -1
console.log('hotdog!'); // this will not log
}
Finally please note that a for...in loop actually should not be used to iterate over arrays -- it really exists to iterate over keys in an object. For iterating over arrays in JS, a classic for loop is the correct approach.
Use the indexOf method.
The in operator checks for the existence of keys, not of values.
You, as well, can use a for..in loop, to iterate over all keys of an object:
for (key in object)
console.log(object[key])
In the case of arrays, it would give the same result as
for (index=0; index<array.length; index++)
console.log(array[i])

JS JSON from URL [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Okey, so I have been trying to figure this out all day and can't see the reason why this dosn't work.
I have a URL that creates this output:
[{"id":"1"},{"id":"2"},{"id":"3"},{"id":"4"},{"id":"5"},{"id":"6"},{"id":"7"},{"id":"8"},{"id":"9"},{"id":"10"},{"id":"11"},{"id":"12"},{"id":"13"},{"id":"14"}]
And in my JS file I have the simple code:
$.getJSON("path_to_url", function(data) {
console.log(data);
});
This gives my this output:
[Object { id="1"}, Object { id="2"}, Object { id="3"}, Object { id="4"}, Object { id="5"}, Object { id="6"}, Object { id="7"}, Object { id="8"}, Object { id="9"}, Object { id="10"}, Object { id="11"}, Object { id="12"}, Object { id="13"}, Object { id="14"}]
I have been trying all day to change my PHP file to generate this a better way and so on, and at the end I just made it this simple.
But how should I "echo" this out from my JS file?
console.log(data.(?));
Thanks in advance, and if you do know of any good and easily understanding docs, please let me know :)
Have a look at jQuery each function https://api.jquery.com/jQuery.each/
$.each(data, function( index, value ) {
console.log(value.id);
});
The objects are in an array. You can just call them like so;
console.log(data[0].id);
console.log(data[1].id);
In this manner you can loop on the list and access each ID.
For a more classical description;
[] is a list (or slice) (an array without a limit)
{} is a dictionary (or map), which can contain multi-dimensional slices
[] are only accessible by their indexes (0, 1, etc.).
As JavaScript doesn't really have classical classes (excluding the Prototyping principle) Objects are simply a dynamic collection of variables and lambs-functions inside a dictionary (map).
Arrays are the most-used data-types on high level languages. They bind bytes to each other. A simple word in C will look like this in Unicode references:
[ 119 111 114 100 ]
This is a simple collection of int8 (byte) where a string-parser knows which letter to show from the character-set.
The 0th item of the Array is an Object, so to display every item you would:
for (var key in data[0]) {
if (data[0].hasOwnProperty(key)) {
console.log(key + " -> " + data[0][key]);
}
}
If you want your PHP file to generate an array of id's then first you need to know the syntax, in the console of your browser you can execute the following command:
console.log(JSON.stringify([1,2,3,4]));//=[1,2,3,4]
So in PHP you can create an Array with the id's
$idArray;//this is the array containing 0=>(id=>1),1=>(id=>2)
$ret;//the array that will return the id's
foreach($idArray as $id){
$ret[]=$id["id"];
};
echo json_encode($ret);//should give the output [1,2,3,4];
In JavaScript you now have an array of numbers, not an array of objects, you can go through them like so:
var i = -1,len = data.length;
while(++i < len){
console.log("id at",i," is:",data[i]);
}

Categories

Resources