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.
CodePudding user response:
In your object, why dont you store the object name, which is a string.
In your categoryList, use the name, instead of the objects, as keys.
CodePudding user response:
You don't get variable names as strings. At best, you'll get to do it the other way round, but really you should never care about variable names as data. You can (and should) inline those 4 const variables in your categories object.
To get the respective value from the other object, use the same keys in both categories and categoryList. That is, either
const categories = {
ctgOne: { test1: …, test2: …},
ctgTwo: { test1: …, test2: …, test3: …},
ctgThree: { test1: …, test3: …},
ctgFour: { test2: …, test3: …},
};
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],
};
or
const categories = {
1: { test1: …, test2: …},
2: { test1: …, test2: …, test3: …},
3: { test1: …, test3: …},
4: { test2: …, test3: …},
};
const categoryList = {
1: [1, 3, 5, 8, 13],
2: [23, 4, 78],
3: [12, 33, 54, 8, 13, 12, 45],
4: [1, 35, 5, 2],
};
but not a mix of them. If you really need both of them, you won't get away without a separate mapping table.
