I'm new to javascript and JSON. I have JSON like this:
data = [[{"checked":false,"no":"1"},{"checked":true,"no":"2"}]]
But I am having a hard time looping through just to get the "checked" value.
I used for loop then i try to console.log data.checked but it always returned undefined. How can do this?
Get first array element using index and use Array#forEach method for iterating.
var data = [
[{
"checked": false,
"no": "1"
}, {
"checked": true,
"no": "2"
}]
];
data[0].forEach(function(v) {
console.log(v.checked);
})
You have a nested array, so to access the checked property of the member objects you'll need to access them at data[0].
let innerData = data[0];
for(let i = 0; i < innerData.length; i++) {
console.log(innerData[i].checked);
}
In your JSON, your have a top-level array, then inside that you have another level of array(s), and in that array you have the objects. So what you should do is something like this.
for (var i = 0; i < data.length; ++i) {
for (var j = 0; j < data[i].length; ++j) {
console.log(data[i][j], data[i][j].checked);
}
}
You could get rid of the double nested array with
array = array[0];
Then loop as you always loop.
// This is array in array with object
var data = [[{"checked":false,"no":"1"},{"checked":true,"no":"2"}]]
for(var i = 0 ; i < data.length ; i++){ // Test the length of first array and go inside
for(var z = 0 ; z < data[i].length ; z++){ // When you are inside the array go to another one array and inside go and search 'chacked'
console.log(data[i][z]['checked']); // show value of the checked
}
}
Related
I am trying to create an array of objects. One object property is a function, which I want to change value of depending on which number in the array the object is.
When I try to use the 'i' value from the for loop, this is not being maintained in the function as a number. It is remaining a variable.
var array = [];
for (var i = 0; i<number; i++){
array[i].someFunction = function(i) {console.log(i)}}
However, when I call the value held in that property (i.e.):
console.log(array[2].someFunction)
It returns {console.log(i)} instead of {console.log(2)} which is what I want it to do.
Basically you had some problems in your code, like:
not defining number
using var instead of let
not defining the object
using the same value as parameter of the function
here you have the working solution.
var array = [];
// numbers was not defined.
const number = 10;
// use let instead of var
for (let i = 0; i < number; i++) {
// you are not instantiating your object, here is an example.
array[i] = {
"foo": "bar",
"index": i,
}
// you have to change i to j, because if you use i
// it will be the parameter of the function
array[i].someFunction = function(j) {
console.log('index: ', i);
console.log('parameter: ', j)
}
}
// we see the function
console.log(array[2].someFunction)
// we call the function succesfully
array[2].someFunction(100);
It's still referencing i, which has since changed to (number - 1). Save the value somewhere you know it's not subject to change- perhaps in the object itself:
var array = [{}, {}, {}];
for(var i = 0; i < array.length; i++){
array[i].index = i;
array[i].someFunction = function(){console.log(this.index);}
}
//and see that it's working...
for(var i = 0; i < array.length; i++){
array[i].someFunction();
}
I am trying my hand at Javascript after learning a number of other coding languages.
*Edit* I fixed the problem, I simply had to use the let keyword in both outer for loops which used i as the same name for the iterator variable.
I have a 2D int array with 29 rows, each of which contains an array of length 744 (744 * 29 = 21576 numbers), and I would like to pass each array, or column, into a method that performs math expressions (i.e the mean of all values, the standard deviation, etc) and log the results to my console. When I attempt to do so, the loop only outputs results of the computation of the numbers in the 1st array, and none of the others. I may be wrong, but I have a feeling the solution may have something to do with awaiting for a result and/or exploiting asynchronous behavior, or my misunderstanding of how to deal with an array as an object.
First and foremost, I have written all of my active code within an fs.readFile method, which reads through a JSON file that provides me with my desired data.
fs.readFile('./doc.json', 'utf-8', (err, text) => {...
The resulting data is an array of objects. The following is the hierarchy of information found within the array. I use a triple for loop to access the desired data and populate my 2D array. (I know that this is not nearly the most efficient way of accomplishing this, but I figure it should work nonetheless)
//Array [
//Object {...
//Property: inner Array[
//inner Object {...
//Desired Property: object which contains the desired values{...}
// },...
// ]
// },...
// ]
for(let i = 0; i < dataArray.length; i++){
for(let j = 0; j < dataArray[i].property.length; j++){
let valueArray = Object.values(dataArray[i].property[j].desiredProperty).slice(0);
for(let c = 0; c < valueArray.length; c++;){
arr[c][(i * dataArray[i].property.length) + j] = valueArray[c];
}
}
}
After populating it, I have no problem iterating through the 2D array and simply logging every array of numbers to the console (the following loop is outside of the previous loop)
for(i = 0; i < arr.length; i++){
console.log("array number " + (i + 1) + ": " + arr[i]);
}
However, when I attempt to pass the same array into a GetTotal method (retrieves the total of all numbers in the array) and store the result, the program outputs the mean of the first array of numbers, and immediately ends.
for(i = 0; i < arr.length; i++){
console.log("array number " + (i + 1) + ": " + arr[i]);
let tot = GetTotal(arr[i]);
console.log("\nTotal: " + tot);
}
function GetTotal(nums){
let sum = 0;
for(i = 0; i < nums.length; i++){
sum += nums[i];
}
return sum;
}
Not quite sure how to post pictures here, I'm sure those would be helpful to better visualize the situation
I initialize my 2D array using a Create2DArray method, then populate each new array with zeroes:
var arr= Create2DArray(numRows, numCols);
for(i = 0; i < arr.length; i++){
for(j = 0; j < arr[i].length; j++){
arr[i][j] = 0;
}
}
function Create2DArray(rows,cols){
let newArr = [];
for(i = 0; i < rows; i++){
newArr.push(new Array(cols));
}
return newArr;
}
I would like to see the result of performing the method's computations on ALL arrays of numbers instead of just the first.
Thanks for your time.
I am not sure of have understood what exactly are you looking for. This would be my approach to this kind of problems :
var dataArray = [
{propertyArr : [{prop1 : 1, prop2 : 2}, {prop1 : 1, prop2 : 2}]},
{propertyArr : [{prop1 : 3, prop2 : 4}, {prop1 : 3, prop2 : 4}]},
{propertyArr : [{prop1 : 5, prop2 : 6}, {prop1 : 5, prop2 : 6}]}
]
var valueArray = [1,2,3,4,5,6,7] ;
var resultValues = dataArray.map((element,i) => {
var arr = element.propertyArr.map((object,j) => {
var value = valueArray[object.prop1] + valueArray[object.prop2] ;
return value ;
})
return arr ;
});
resultValues.forEach((elementArr,i) => {
elementArr.forEach((element2Arr,j)=>{
console.log(`resultValues[${i},${j}] : [${resultValues[i][j]}]`) ;
})
})
For example i've created an array in a for loop:
for (i = 0; i < data.length; i++){
array[i] = {
label: bread,
color: colorArray[i]
};
}
In a child for loop i'd like to append more data to this array. What I tried:
for (r = 0; r < data[i].length; r++){
array[i].push({
data: breadTypes[r][i]
});
}
Which throws TypeError : array[i].push is not a function.
array[r] = { data: breadTypes[r][i] }; overwrites the existing data as expected.
Is there a different way to do this? Thanks!
Here array[i] is an object and push is an array method which cannot be used on an object but you can create data key in array[i] object
array[r].data = breadTypes[r];
If the second loop is not nested inside the first one then breadTypes[r][i] will throw an error since i will be be available
Just do like this:
for (i = 0; i < data.length; ++i) {
array[i].data = breadTypes[i];
}
If i understand correctly, your second for should look like this:
for (r = 0; r < data[i].length; r++){
array[i].data = breadTypes[r][i];
}
I have an array of data as follows:
var Sonuc = [[{"ID":8,"Number":"1","Name":"Ahmet"}],
[{"ID":7,"Number":"2","Name":"Semih"}],
[{"ID":6,"Number":"3","Name":"Derviş"}],
[{"ID":8,"Number":"4","Name":"Derviş"},{"ID":9,"Number":"4","Name":"Veli"}],
[{"ID":11,"Number":"44","Name":"Zeki"},{"ID":45,"Number":"44","Name":"Veli"}]]
I tried to write datas to console for each object as follows, but it does not work:
for (var i = 0; i < 3; i++) {
for(var obj in Sonuc[i]) {
console.log(obj.Number);
};
}
How can I output the Number value for each data on console?
The problem is that you have an array or arrays, with the sub-arrays each containing one or more objects.
Your problem is you are not specifying the index for the sub-arrays. You can access the first object like this:
console.log(obj[0].Number);
That will get you some output at at least, but it is confusing exactly what data you want to get. That 3 loop makes no sense...
If you want to output all objects, then you should first loop the sub-arrays, and then loop the objects. Something like this:
var Sonuc = [[{"ID":8,"Number":"1","Name":"Ahmet"}],
[{"ID":7,"Number":"2","Name":"Semih"}],
[{"ID":6,"Number":"3","Name":"Derviş"}],
[{"ID":8,"Number":"4","Name":"Derviş"},{"ID":9,"Number":"4","Name":"Veli"}],
[{"ID":11,"Number":"44","Name":"Zeki"},{"ID":45,"Number":"44","Name":"Veli"}]];
for (var i = 0; i < Sonuc.length; i++) {
var arr = Sonuc[i];
for (var j = 0; j < arr.length; j++) {
var obj = arr[j];
console.log(obj.Number);
}
}
I want to push array A to B inside cycle and then and for every iteration of B i need to delete array A and create new one. I get all data before clearing the array, but after clearing I get array B with empty values
Code :
for (i = 0; i < XArray.length; i++) {
var pointsArray = [];
for (j = 0; j < XArray.length; j++) {
if (XArray[i] == XArray[j]) {
pointsArray.push([parseFloat(YArray[i]), parseFloat(ZArray[i])]);
}
}
dataSource.push({
name: i,
data: pointsArray
});
pointsArray.length = 0;
}
The last line
pointsArray.length = 0;
removes every element in the array you created in the first line. And since all objects are assigned by reference (and arrays are objects), the data property of the object will now point to an empty array. Here is a simplified example:
var a = [1, 2];
var b = a;
a.length = 0;
console.log(b); // [] -- an empty array
So, your current code has the same effect as
dataSource.push({
name: i,
data: []
});
Solution: Just remove the last line and it will work as expected.