0

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.

Mr Day2Day
  • 73
  • 1
  • 7

1 Answers1

4

If you want to be able to combine properties, either use an array of properties, or join all properties by .. Then, to retrieve the nested value, use one of the methods at Accessing nested JavaScript objects and arays by string path:

const level_1 = {
  level_2: {
    level_3: "level_3",
    level_4: "level_4",
    level_5: {
      level_6: "level_6",
    },
  },
};

var a = "level_2";
var b = "level_3";

const c = [a, b];
const getNested = (obj, props) => props.reduce((a, prop) => a[prop], obj);

console.log(level_1[a]);
console.log(level_1[a][b]);
console.log(getNested(level_1, c));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • This was VERY helpful, I noted this. I have edited my question please have a look. Your answer was exactly what i was looking for. – Mr Day2Day Sep 07 '20 at 16:55