0

Why am I unable to read the following variables in a nested map?

for (const key in doc.data().category) {
  const location = doc.data().location;  // declared but it's value is never read"
  const mainCategory = doc.data().category; // declared but it's value is never read"
  const subCategory = doc.data().category[key]; // declared but it's value is never read"

  categoryCount.doc('categoryCount')
  .set({ location: { mainCategory: { subCategory: "test" } } }, 
  { merge: true })
  .catch((error) => console.log(error));

Console logs to clarify:

console.log(location); // "New York"
const map = { location: { mainCategory: { subCategory: true } } };
console.log(map);  // "location": {"mainCategory": {"subCategory": true}}
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Mr Jax
  • 957
  • 12
  • 22
  • I'm having a hard time understanding what the problem is. What do you mean by "declared but it's value never read"? – Doug Stevenson Dec 02 '19 at 17:27
  • @DougStevenson I've added console logs to clarify. I can't get the values when using the variables in a map. The TSLint error is "declared but it's value is never read". – Mr Jax Dec 02 '19 at 17:44
  • What do you expect the code to do instead of what it's doing now? – Doug Stevenson Dec 02 '19 at 17:50
  • @DougStevenson Return the actual data of the variable, not variable name. So, return "New York": {"Running": {"Race":true}}, instead of "location": {"mainCategory": {"subCategory": true}} – Mr Jax Dec 02 '19 at 17:56

2 Answers2

2

If you want to use the value of a variable as the name of a property, you have to tell JavaScript that you want to insert that value (as opposed to just naming the key):

{ [location]: { mainCategory: { subCategory: "test" } } }

Notice the square brackets around location.

See also: Square Brackets Javascript Object Key

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
0

I think you may be misunderstanding how JavaScript objects work. Imagine you have three variables called:

var A = 'X';
var B = 'Y';
var C = 'Z';

when you code:

{
  A: {
    B: {
      C: "test"
    }
  }
}

You do not end up with an object of value:

{
   X: {
     Y: {
       Z: "test"
     }
   }
}

If that is what you want, consider:

var O1 = {};
O1[C] = "test";
var O2 = {};
O2[B] = O1;
var O3 = {};
O3[A] = O2;

// O3 is the top level object
Kolban
  • 13,794
  • 3
  • 38
  • 60