I'm building my first framework. I need to be able to generate a semi-dynamic object, to which end, I want to re-use a single variable that points to a unique-value-returning function. I have a JS object literal like this:
let myObject = {
[test] : "placeholder text 1",
[test] : "lorem ipsum 2"
};
The [test] bit refers to a function of this sort:
const test = (function() {
return String("morePlaceholderText" + getRandInt() )
})();
const validatorCache = new Set();
let max;
function getRandInt() {
let length = validatorCache.size;
const initMax = 15; // set the starting maximum value
if(length < initMax){ // determine the mode of setting the maximum value
max = initMax;
} else {
max++
//max = max + 20; // alternatively, jump the pool up by a fixed amount when the ceiling is reached.
};
const min = 1; // set the starting minimum value - if desired.
let newRand;
do {
newRand = Math.floor(Math.random() * (max - min + 1)) + min;
} while (validatorCache.has(newRand)); // Validate against cache
validatorCache.add(newRand); // Add to cache
return newRand;
};
console.log(getRandInt());
But if I console.log it after running this, I get only one of the properties:
console.log(JSON.stringify(myObject));
{"morePlaceholderText7":"lorem ipsum 2"}
Demo:
const test = (function() {
return String("morePlaceholderText" + getRandomInt() )
})();
function getRandomInt() {
return Math.floor(Math.random() * 15);
};
let myObject = {
[test] : "placeholder text 1",
[test] : "lorem ipsum 2"
};
console.log(JSON.stringify(myObject));
So far, I've tried several different structures. It didn't seem to like arrow functions. Doesn't work at all without the square brackets on the property name function.
I could get a similar effect by simply storing a specific property inside my object, with unique object identifier metadata stored as to the value, and I did try that... But the readability impact was so severe on some of the more complex data structures, that got scrapped out as an absolute last ditch resort. If I can get something that's pretty close in brevity and readability to what I have here, that would be ideal.
Do I have something wrong with my syntax somewhere? Having a tough time finding documentation on this sort of thing.
String(). The+operator returns a string when either of the arguments is a string.let myObject = ["placeholder text 1", "lorem ipsum 2"];. Though if you're convinced you want random keys then you could use randomUUID{[crypto.randomUUID()]: "value"}