object.js
var a = "level_2";
var b = "level_3";
var c;
const nums = [1, 2, 3, 4];
const num_1 = nums[Math.floor(Math.random() * nums.length)];
const num_2 = nums[Math.floor(Math.random() * nums.length)];
console.log({ num_1, num_2 });
if (num_1 <= num_2) {
c = [a];
} else {
c = [a][b];
}
/**
* Lets say I make a database call, the result is from a promise I use '.then()'
* eg:
* ...
* .then(level_1 => {
* let final;
* final = level_1[c]
* res.statusCode(200).json({ final })
* })...
*
* This is what I'm trying to achieve where I can determine the object property
* how deep in the object I would like to go before I get the object.*/
const level_1 = {
level_2: {
level_3: "level_3",
level_4: "level_4",
level_5: {
level_6: "level_6",
},
},
};
console.log("\nPrint 1:\n", level_1[a]);
console.log("\nPrint 2:\n", level_1[a][b]);
console.log("\nPrint 3:\n", level_1[c]);
The if statement shows the randomness I'll be dealing with when it comes to which information I need from the object.
Result 1:
This does not work when c
is [a][b]
$ node object.js
{ num_1: 4, num_2: 1 }
Print 1:
{
level_3: 'level_3',
level_4: 'level_4',
level_5: { level_6: 'level_6' }
}
Print 2:
level_3
Print 3:
undefined
Result 2:
This works well when c
if only [a]
$ node object.js
{ num_1: 2, num_2: 3 }
Print 1:
{
level_3: 'level_3',
level_4: 'level_4',
level_5: { level_6: 'level_6' }
}
Print 2:
level_3
Print 3:
{
level_3: 'level_3',
level_4: 'level_4',
level_5: { level_6: 'level_6' }
}
How do I get c
to work? As you can see Result 1
returns undefined for c
This has been puzzling me for a while now and it would make my code very efficient if someone could help me with this.