I have been searching around and in most forums the reply to this question is more or less that it's unnecessary to convert a variable into string. However given the following scenario how could I go about solving the problem?
I have an object categories as follows:
const categories = {
1: ctgOne,
2: ctgTwo,
3: ctgThree,
4: ctgFour,
};
These categories correspond to objects which contain some arbitrary data:
const ctgOne = {
test1: ["blah", "blah", "blah"],
test2: ["blah", "blah", "blah"],
};
const ctgTwo = {
test1: ["blah", "blah", "blah"],
test2: ["blah", "blah", "blah"],
test3: ["blah", "blah", "blah"],
};
const ctgThree = {
test1: ["blah", "blah", "blah"],
test3: ["blah", "blah", "blah"],
};
const ctgFour = {
test2: ["blah", "blah", "blah"],
test3: ["blah", "blah", "blah"],
};
I have another object categoryList containing some numbers associated to each category in arrays:
const categoryList = {
ctgOne: [1, 3, 5, 8, 13],
ctgTwo: [23, 4, 78],
ctgThree: [12, 33, 54, 8, 13, 12, 45],
ctgFour: [1, 35, 5, 2],
};
When I run the following script, I get an error for the second console.log(count); for obvious reasons because in count = categoryList[categoryName].length; "categoryName" is required to be a string. However, if I convert the categories in my categories object to strings, console.log(keys); gives me the length of the string instead of the number of keys in the object.
let categoryNumber = 1;
let categoryName = categories[categoryNumber];
let keys = Object.keys(categoryName).length;
console.log(keys);
count = categoryList[categoryName].length;
console.log(count);
What would be the best approach to solve this dilemma? I want to count the number of keys in the object as well as the numbers in the categoryList.
1,2, ... as category keys? why not takectgOne, etc as keys?1,2, etc as keys forcategoryList? it is the same to take numbers instead of nonmeaningful names.