Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic object value for gender in Javascript

I'm trying to write something that loads text from an object and randomly assigns gender in a way that persists

const output = {
  text: "He thought that his sweater would suit him"
}

I'd like to be able to have the object, when displayed, show "He thought that his sweater would suit him" or "She thought that her sweater would suit her" at random. In attempting to solve this without having to essentially create two different objects--one for male, one for female--I've gotten this far:

const gender = {
  male: {
    pronoun: "he",
    possPronoun: "his",
    possAdjective: "his",
    object: "him",
    moniker: "sir"
  },
  female: {
    pronoun: "she",
    possPronoun: "hers",
    possAdjective: "her",
    object: "her",
    moniker: "ma'am"
  }
};

function randGender (usage) { // Add lettercase functionality later
  return Math.floor(Math.random()*2) == 1 ? gender.female[usage] : gender.male[usage] 
}

console.log(randGender("pronoun"));

Where I get stuck is what to do after this.

const output = {
  text: `${randGender("pronoun")} thought that ${randGender("possAdjective")} sweater would suit ${randGender("object")}`
}

console.log(output.text); //she thought that his sweater would suit her

...obviously doesn't work when I want it kept to all one gender.

I think there are workarounds, such as having output.text.male and output.text.female and doing the random piece when calling the object. Are there any ways to do it in the way I've laid out?

Thanks for any help!

like image 814
Michael Avatar asked May 15 '26 02:05

Michael


1 Answers

You'll need to return the whole inner object for a gender instead of certain props and based on that you can retrieve the props inside the object:

function getRandGender() {
  return Math.floor(Math.random() * 2) == 1 ? gender.female : gender.male
}

const randGender = getRandGender();

const output = {
  text: `${randGender.pronoun} thought that ${randGender.possAdjective} sweater would suit ${randGender.object}`
}
like image 160
Clarity Avatar answered May 16 '26 14:05

Clarity