Undefined value with declared values JavaScript - javascript

So here's the problematic code
var board = [
{
grdNbr: 1,
value: 0,
},
{
grdNbr: 2,
value: 0,
},
{
grdNbr: 3,
value: 0,
},
{
grdNbr: 4,
value: 0,
},
{
grdNbr: 5,
value: 0,
},
{
grdNbr: 6,
value: 0,
},
{
grdNbr: 7,
value: 0,
},
{
grdNbr: 8,
value: 0,
},
{
grdNbr: 9,
value: 0,
},
]
I tried declaring objects as arrays, but I don't really get how it works, so please explain it to me. So, back to the topic. When I check the value it shows undefined (the code is below)
switch(board.grdNbr){
case 1:
board.value = 1
console.log(board.value)
bg.bg1 = x
msg.channel.send(boardDRW)
turn++
break;
...
}
After that, in the console log the value for value is 1, but before that the value is undefined. Any idea how can I fix this?

Your problem is your board variable is an array of object, and you try to access directly a parameter of the array without specifying what object of the array you wanna access.
Instead of trying to access a value with board.value, you should use board[index].value with index being the index of the object in that list (exemple : board[0].value)

Before I begin, I want to thank you that you spent some time helping me out. I found a solution to my problem with a different code, so I'm very sorry for wasting your time.
Have a nice day!
Abyzls

Related

How to rename properties in objects that are in an array. What is the right way to solve the task?

I need to build diagram,
There is an array with objects for chart data
"graphicDetails": [
{
"hour": 0,
"businessOperationPlansTotalDemand": 8.201753196882908,
"employeesCount": 0,
"businessOperationPlans": [
{
"name": "operation0",
"value": 5.999355066255491
},
]
},
{
"hour": 1,
"businessOperationPlansTotalDemand": 7.450044665662842,
"employeesCount": 3,
"businessOperationPlans": []
},
{
"hour": 2,
"businessOperationPlansTotalDemand": 5.814536267254451,
"employeesCount": 5,
....
To draw it in the chart library (chartjs) I need the object to be with the fields {x: hour, y: businessOperationPlansTotalDemand, etc.}. Example:
data: [
{ x: 0, y: 5.815634, businessOperationPlans: [{operation: ...}] ,
{ x: 1, y: 2.23232, businessOperationPlans: [{operation2: ...}] ,
...
]
I know i can use forEach or something like this to rename properties, but what is the right way to resolve this task? maybe i should ask backend to make data in other format?
Maybe I need to create a new array based on this with other properties and put it in the computed field in Vue? How can i do this?
You can use map
The map() method creates a new array with the results of calling a
provided function on every element in the calling array.
const graphicDetails = [{
"hour": 0,
"businessOperationPlansTotalDemand": 8.201753196882908,
"employeesCount": 0,
"businessOperationPlans": [{
"name": "operation0",
"value": 5.999355066255491
}, ]
},
{
"hour": 1,
"businessOperationPlansTotalDemand": 7.450044665662842,
"employeesCount": 3,
"businessOperationPlans": []
}
];
const newData = graphicDetails.map(a=>{
return {x:a.hour,y:a.businessOperationPlansTotalDemand,businessOperationPlans:a.businessOperationPlans };
})
console.log(newData);
You can create a new array and design as per your new array structure . If you are using any backend , create the structure from there and process the same in computed , rather put it in mounted so it will load the same in the component gets mounted . Best way will be to process the data-set from backend .

node.js: iterate through nested firebase JSON tree

I am trying to access a nested firebase tree from node.js as follows.
ref.forEach( function(snapshot0) {
snapshot0.child("Meals").forEach( function(snapshot1) {
console.log(snapshot1.val);
});
});
And it will just always tell me that ref.forEach is not a function.
TypeError: refPrices.forEach is not a function
I have defined these as follows.
var db = admin.database();
var ref = db.ref("users");
I have checked these answers
How do I iterate through a large dataset with Firebase / Node.js?
Iterating through nested firebase objects - Javascript
Iterate through nested JSON tree and change values
But I believe according to those my above code should be working, so I am really confused. Also, I have tried to replace forEach by a loop, but I get
TypeError: ref.length is not a function
so I cannot calculate the maximum value of the loop. I have also tried
ref.once("value", function(snapshot0) {
snapshot0.child("Meals").forEach( function(snapshot1) {
console.log(snapshot1.val);
});
});
but in that case it throws the error
TypeError: snapshot0.forEach is not a function
so I pretty much still have the same problem. I cannot work out where my example is different from the links to the solutions above?
Edit: here is what my JSON tree looks like (as per Frank's request). I have only shortened the userID's a little bit.
"users" : {
"ugkvjTuXW2" : {
"Meals" : {
"Meal_2" : {
"priceHist" : [ null, 1, 1, 1, 1, 1, 1 ]
},
"Meal_3" : {
"priceHist" : [ null, 1, 1, 1, 1, 10, 1 ]
},
"Meal_4" : {
"priceHist" : [ null, 1, 1, 1, 1, 1, 1 ]
},
"Meal_5" : {
"priceHist" : [ null, 1, 1, 1, 1, 1, 1 ]
}
}
},
"oJJ1Cojia2" : {
"Meals" : {
"Meal_2" : {
"priceHist" : [ null, 1, 4, 4, 1, 1, 1 ]
},
"Meal_3" : {
"priceHist" : [ null, 1, 1, 1, 1, 10, 1 ]
},
"Meal_4" : {
"priceHist" : [ null, 1, 5, 1, 1, 7, 1 ]
},
"Meal_5" : {
"priceHist" : [ null, 3, 1, 1, 1, 12, 1 ]
}
}
}
}
On your first snippet: a DatabaseReference is nothing more than the path of some data in your Firebase Database. The data itself is not in the ref, so you can't loop over the data.
It's hard to say what's going wrong in your second snippet, because we have no idea what the data under /users looks like. Please edit your question to include a minimal snippet of the JSON (as text, no screenshots please) that is necessary to reproduce the problem. You can get this by clicking the "Export JSON" link in your Firebase Database console.
Update
If you retrieve the value of /users, you get a snapshot with all users. So the first level of children are a node for each user. Then under there you have the meals for each user. Your code is missing a loop for the first level, so:
var ref = admin.database().ref("users");
ref.once("value", function(userSnapshot) {
userSnapshot.forEach(function(userSnapshot) {
userSnapshot.child("Meals").forEach(function(mealSnapshot) {
console.log(mealSnapshot.val());
});
});
});
Also note that you're using numeric indexes, which Firebase recommends against. See this blog post on arrays and the Firebase documentation on handling collections.

Accessing specific values in JSON object

I can't figure out what I'm doing wrong when accessing this JSON object:
{ Items:
[ { mId: 'who' },
{ mId: 'am' },
{ mId: 'I' } ],
Count: 3,
ScannedCount: 3 }
{ Items:
[ { cId: 'big' },
{ cId: 'scary' },
{ cId: 'muppet' } ],
Count: 3,
ScannedCount: 3 }
This is the object I am getting back from a function and I'm trying to access the individual items to update their values.
When I want to print 'who' for example, I do this:
console.log(obj.Items[0].mId)
Now I expect to get 'who' back, but this is what prints:
undefined
who
That 'undefined' always tags along. What am I doing wrong here?
Also, if I try to change the value somewhere by doing:
obj.Items[0].mId = 'x'
This happens:
{ Items:
[ { mId: 'x' },
{ mId: 'am' },
{ mId: 'I' } ],
Count: 3,
ScannedCount: 3 }
{ Items:
[ { cId: 'big', mId: 'x' },
{ cId: 'scary' },
{ cId: 'muppet' } ],
Count: 3,
ScannedCount: 3 }
This is not what I want.. I don't understand how to access only the first 'Items'. It seems like I'm accessing both.
Any help or advice is greatly appreciated. I probably don't need to say that I'm not very used to working with JSON.
For the undefined issue, please see the answer here: What does it mean if console.log(4) outputs undefined in Chrome Console? but TL;DR you're just seeing the 'undefined' return from console.log(), because it has no return value. It shouldn't be an issue once you're not working in the console.
As for how you have 2 separate objects both called obj, I don't understand, as other said in the comments, please post the full code so we can see how this is being used/generated.
Also for clarification it looks like you're working with JavaScript objects, not JSON, similar but not the same.

Eloquent Javascript: Exercise: A list

I am learning JavaScript from a book called 'Eloquent Javascript'
I'm trying to solve the exercise described here: http://eloquentjavascript.net/04_data.html#h_nSTX34CM1M
I managed to work out that this code works:
function arrayToList(array) {
var list = null;
for (var i = array.length - 1; i >= 0; i--)
list = {
value: array[i],
rest: list
};
return list;
}
console.log(arrayToList([1, 2, 3]));
Result: { value: 1, rest: { value: 2, rest: { value: 3, rest: null } } }
So far, so good, and according to the book this is the right solution. BUT!
When I try to run the same thing but instead with a longer array, let's say:
console.log(arrayToList([1, 2, 3, 4, 5]));
The result is: { value: 1, rest: { value: 2, rest: { value: 3, rest: [Object] } } }
Why is this? Is my code wrong?
There's nothing wrong with a longer array. console.log() is a non-standard, browser-specific implementation and some implementations set a cap on how many levels of object nesting they will display. When they hit that level, they just display [Object] rather than recurse into it to show deeper nesting.
If you actually set a breakpoint and examine your variable in the debugger, you will see you can expand the nested levels as deep as it goes and see everything.
Or, you could do this:
console.log(JSON.stringify(arrayToList([1, 2, 3, 4, 5])));
to manually convert the whole thing to a string before using console.log() on it.

Trying to get a variable to equal an object from a set of objects...i think?

OK so the way i worded this question before must have been too convoluted so here is a simplified version:
I have a variable which equals:
{
txid: 'f0315ffc38709d70ad5647e22048358dd3745f3ce3874223c80a7c92fab0c8ba',
version: 1,
locktime: 0,
vin:
[ { coinbase: '0420e7494d017f062f503253482f',
sequence: 4294967295 } ],
vout: [ { value: 50, n: 0, scriptPubKey: [Object] } ],
blockhash: '00000000b873e79784647a6c82962c70d228557d24a747ea4d1b8bbe878e1206',
confirmations: 39288,
time: 1296688928,
blocktime: 1296688928 }
I want to make another variable equal just:
vout: [ { value: 50, n: 0, scriptPubKey: [Object] } ],
How do i do this?
When i try:
varible2 = variable1.vout
I get back an error saying ".vout" is undefined
var avariable = {/* your object [literal] here */};
var anothervariable = avariable.vout; // or avariable["vout"]
// or did you want the following?
var anothervariable = {
vout: avariable.vout
};

Categories