Get key Json and search with name var [duplicate] - javascript

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 7 years ago.
I have the following problem:
I have the following JSON:
var words = {
"categorias": [
{
"Licores": ["Smirnoff", "Johnnie Walker", "Bacardi", "Martini", "Hennessy", "Absolut", "Jack Daniels", "Chivas Regal", " Baileys", "Ballantines", "CAPTAIN MORGAN", "CUERVO", "JAEGERMEISTER", "MOET ET CHANDON", "DEWARS", "JIM BEAM", "GALLO", "HARDYS", "CROWN ROYAL", "RICARD", "CONCHA Y TORO", "GREY GOOSE", "GORDONS", "GRANTS", "JAMESON", "MALIBU", "STOLICHNAYA", "MARTELL", "HAVANA CLUB", "REMY MARTIN", "PATRON", "YELLOWTAIL", "SAUZA", "SKYY", "FINLANDIA", "BERINGER", "TANQUERAY", "DREHER", "BEEFEATER", "BOMBAY", "SEAGRAM", "CANADIAN CLUB", "GLENFIDDICH", "COINTREAU", "TEACHERS", "KAHLUA", "BELLS", "CINZANO VERMOUTH", "LINDEMANS", "COURVOISIER", "CANADIAN MIST", "TORRES", "INGLENOOK", "CASTILLO", "KUMALA", "PENFOLDS", "LANSON", "Ron", "Vodka", "Whisky", "Bourbon", "Brandy", "Cognac", "Tequila", "Ginebra", "Vino blanco", "Vino tinto", "Champagne", "Cerveza", "Budweiser", "Heineken", "Sambuca", "Frangelico", "Triple Sec", "Licor de cafe", "Kirsch", "Fernet", "Aguardiente", "Pisco", "Sangría", "Mojito", "Margarita", "Cuba libre", "Daiquiri", "Cosmopolitan", "Caipirinha", "White Russian", "Coco Loco", "Mai Tai", "Manhattan", "Zombie", "Gintonic", "Hurricane", "Negroni", "Paloma", "Farnell"]
},
{
"animales": ["Abadejo", "Abanto", "Abeja", "Abeja doméstica", "Abejorro", "Abubilla", "Abulón", "Acedía", "Acentor", "Acevia", "Acocil", "Acranio", "Actinia", "Addax", "Agachadiza", "Aguará", "Águila", "Agutí", "Ajolote", "Alacrán", "Albatros", "Alburno", "Alcaraván", "Alcatraz", "Alcaudón", "Alce", "Alcélafo", "Alimoche", "Almeja", "Alondra ibis", "Alosa", "Alpaca", "Alzacola", "Ameba", "Ampelis", "Anaconda", "Anchoa", "Anfioxo", "Angelote", "Anguila", "Aninga", "Anoa", "Anolis", "Ánsar", "Anta", "Antílope", "Araguato", "Araña", "Arapaima", "Arapapa", "Ardilla", "Arenque", "Argonauta", "Armadillo", "Armiño", "Arrendajo", "Asno", "Atún", "Avefría", "Avestruz", "Avispa", "Avetoro", "Avispón", "Avoceta", "Avutarda", "Ayeaye", "Ayu", "Babirusa", "Babosa", "Babuino", "Bacalao", "Baiji"]
}
]
}
So when I want search a Categoria I call this function:
function random(max){
return Math.floor((Math.random() * max) + 0);
}
Now as the Key of JSON is a array (categorias), and this key i want get of way random, then i use Object.keys(), and it runs smoothly, when i assigned the var namKeyJson to Object.keys(words.categorias[randomCategory]), i returned the name of the key which i need
var lengthCategory = words.categorias.length-1;
var randomCategory = random(lengthCategory);
var nameKeyJson = Object.keys(words.categorias[randomCategory]);
nameKeyJson = nameKeyJson.toString();
the problem is when i want get the values or the length the categorys of array, and that by placing the variable nameKeyJson, takes the name of the variable but not its value.
var lengthPregunta = words.categorias[randomCategory].nameKeyJson.length;
console.log(lengthPregunta);
Thanks for help me.

var lengthPregunta = words.categorias[randomCategory].nameKeyJson.length;
Should be
var lengthPregunta = words.categorias[randomCategory][nameKeyJson].length;
You try to call 'nameKeyJson' from words.categorias[randomCategory] instead of indexing key by nameKeyJson.

Use bracket notations:
words.categorias[randomCategory][nameKeyJson]
and with your code it will always return only first variable.
So change
var lengthCategory = words.categorias.length-1; to
var lengthCategory = words.categorias.length;
var words = {
"categorias": [{
"Licores": ["Smirnoff", "Johnnie Walker", "Bacardi", "Martini", "Hennessy", "Absolut", "Jack Daniels", "Chivas Regal", " Baileys", "Ballantines", "CAPTAIN MORGAN", "CUERVO", "JAEGERMEISTER", "MOET ET CHANDON", "DEWARS", "JIM BEAM", "GALLO", "HARDYS", "CROWN ROYAL", "RICARD", "CONCHA Y TORO", "GREY GOOSE", "GORDONS", "GRANTS", "JAMESON", "MALIBU", "STOLICHNAYA", "MARTELL", "HAVANA CLUB", "REMY MARTIN", "PATRON", "YELLOWTAIL", "SAUZA", "SKYY", "FINLANDIA", "BERINGER", "TANQUERAY", "DREHER", "BEEFEATER", "BOMBAY", "SEAGRAM", "CANADIAN CLUB", "GLENFIDDICH", "COINTREAU", "TEACHERS", "KAHLUA", "BELLS", "CINZANO VERMOUTH", "LINDEMANS", "COURVOISIER", "CANADIAN MIST", "TORRES", "INGLENOOK", "CASTILLO", "KUMALA", "PENFOLDS", "LANSON", "Ron", "Vodka", "Whisky", "Bourbon", "Brandy", "Cognac", "Tequila", "Ginebra", "Vino blanco", "Vino tinto", "Champagne", "Cerveza", "Budweiser", "Heineken", "Sambuca", "Frangelico", "Triple Sec", "Licor de cafe", "Kirsch", "Fernet", "Aguardiente", "Pisco", "Sangría", "Mojito", "Margarita", "Cuba libre", "Daiquiri", "Cosmopolitan", "Caipirinha", "White Russian", "Coco Loco", "Mai Tai", "Manhattan", "Zombie", "Gintonic", "Hurricane", "Negroni", "Paloma", "Farnell"]
}, {
"animales": ["Abadejo", "Abanto", "Abeja", "Abeja doméstica", "Abejorro", "Abubilla", "Abulón", "Acedía", "Acentor", "Acevia", "Acocil", "Acranio", "Actinia", "Addax", "Agachadiza", "Aguará", "Águila", "Agutí", "Ajolote", "Alacrán", "Albatros", "Alburno", "Alcaraván", "Alcatraz", "Alcaudón", "Alce", "Alcélafo", "Alimoche", "Almeja", "Alondra ibis", "Alosa", "Alpaca", "Alzacola", "Ameba", "Ampelis", "Anaconda", "Anchoa", "Anfioxo", "Angelote", "Anguila", "Aninga", "Anoa", "Anolis", "Ánsar", "Anta", "Antílope", "Araguato", "Araña", "Arapaima", "Arapapa", "Ardilla", "Arenque", "Argonauta", "Armadillo", "Armiño", "Arrendajo", "Asno", "Atún", "Avefría", "Avestruz", "Avispa", "Avetoro", "Avispón", "Avoceta", "Avutarda", "Ayeaye", "Ayu", "Babirusa", "Babosa", "Babuino", "Bacalao", "Baiji"]
}]
}
function random(max) {
return Math.floor((Math.random() * max) + 0);
}
var lengthCategory = words.categorias.length;
var randomCategory = random(lengthCategory);
var nameKeyJson = Object.keys(words.categorias[randomCategory]);
var lengthPregunta = words.categorias[randomCategory][nameKeyJson].length;
console.log(lengthPregunta);

Related

How can I select a random object from an array and then remove it so it doesn't get repeated?

I'm beginner Javascript student and have to make a trivia game. I have an array of objects which are questions. I want to randomly select an object(question) and then use it, and then get rid of it so that it doesn't get brought up again when I pick the next question. How can I do this correctly? What I have tried so far is:
class Question
{
constructor(t,oA,oB,oC,oD,ans)
{
this.title=t;
this.optionA=oA;
this.optionB=oB;
this.optionC=oC;
this.optionD=oD
this.answer=ans;
}
displayQuestion1R1()
{
userAnswer=prompt(`${this.title}\nA.${this.optionA}\nB.${this.optionB}\nC.${this.optionC}\nD.${this.optionD}`);
}
}
Round1Questions.push(new Question("According to scientists, how old,
approximately, is Earth?", "3 billions years", "100 million years", "4.5
billion years","2.5 billion years", "4.5 billion years"));
Round1Questions.push(new Question("Who was the first American President?",
"Benjamin Franklin", "Barack Obama", "George Washington","Thomas Jefferson",
"George Washington"));
Round1Questions.push(new Question("How many Presidents have there been up to
this year?(2019)?", "45", "40", "60","46", "45"));
Round1Questions.push(new Question("What is the largest Ocean in the world?",
"Atlantic Ocean", "Pacific Ocean", "Indian Ocean","Arctic Ocean", "Pacific
Ocean"));
Round1Questions.push(new Question("Which one of the following is not a
Marvel super-hero?","Spider-Man","Hulk","Batman", "Iron Man", "Batman"));
let ri=RoundQuestions1[Math.floor(Math.random()*Round1Questions.length)];
let question1R1=Round1Questions.splice(ri, 1);
question1R1.displayQuestion1R1();
When I try to run this it says question1R1.displayQuestion1R1() is not a function. However if I remove the splice method I have and just do
let question1R1=RoundQuestions1[Math.floor(Math.random()*Round1Questions.length)];
and then do question1R1.displayQuestion1R1() then it works. However that doesn't allow me to remove the question from the array. How can I accomplish this?
Ok Jack Bashford was close too, but splice method return a array value.
class Question {
constructor(t, oA, oB, oC, oD, ans) {
this.title = t;
this.optionA = oA;
this.optionB = oB;
this.optionC = oC;
this.optionD = oD
this.answer = ans;
}
displayQuestion1R1() {
// userAnswer = prompt(`${this.title}\nA.${this.optionA}\nB.${this.optionB}\nC.${this.optionC}\nD.${this.optionD}`);
console.log( `${this.title}\nA.${this.optionA}\nB.${this.optionB}\nC.${this.optionC}\nD.${this.optionD}` )
}
}
var Round1Questions = [];
Round1Questions.push(new Question("According to scientists, how old, approximately, is Earth ? ",
"3 billions years ", "100 million years ", "4.5 billion years ","2.5 billion years ",
"4.5 billion years ")
);
Round1Questions.push(new Question("Who was the first American President?",
"Benjamin Franklin", "Barack Obama", "George Washington", "Thomas Jefferson",
"George Washington")
);
Round1Questions.push(new Question("How many Presidents have there been up to this year ? (2019) ? ",
"45", "40", "60","46",
"45")
);
Round1Questions.push(new Question("What is the largest Ocean in the world?",
"Atlantic Ocean", "Pacific Ocean", "Indian Ocean", "Arctic Ocean",
"Pacific Ocean ")
);
Round1Questions.push(new Question("Which one of the following is not a Marvel super - hero ? ",
" Spider-Man", "Hulk", "Batman", "Iron Man",
"Batman ")
);
do {
let
PickQuestion_N = Math.floor(Math.random() * Round1Questions.length),
PickedQuestion = Round1Questions.splice(PickQuestion_N, 1)[0]
;
PickedQuestion.displayQuestion1R1();
} while (Round1Questions.length > 0)
Problem
Your approach does not work because of two reasons:
You used RoundQuestions1[Math.floor(Math.random()*Round1Questions.length)] to get your Question instance to assign to r1 variable. Then, you use that instance in Round1Questions.splice(ri, 1), which is not the expected argument type of Array.prototype.splice method.
Round1Questions.splice(ri, 1) returns an Array. So your question1R1 is an array instead of a Question.
Solution
Instead of getting a random Question, try getting a random Quesiton index instead.
Use the random index to splice the Question bank.
Get the first item of the array returned from .splice. See why here.
Working code below (see comments for explanation):
class Question {
constructor(t, oA, oB, oC, oD, ans){
this.title = t;
this.optionA = oA;
this.optionB = oB;
this.optionC = oC;
this.optionD = oD
this.answer = ans;
}
displayQuestion1R1(){
const { title, optionA, optionB, optionC, optionD } = this;
const userAnswer = prompt(`
${title}
A. ${optionA}
B. ${optionB}
C. ${optionC}
D. ${optionD}
`);
}
}
const Round1Questions = [
new Question(
"According to scientists, how old, approximately, is Earth?", "3 billions years",
"100 million years",
"4.5 billion years",
"2.5 billion years",
"4.5 billion years"
),
new Question(
"Who was the first American President?",
"Benjamin Franklin",
"George Washington",
"Thomas Jefferson",
"George Washington"
),
new Question(
"How many Presidents have there been up to this year (2019)?",
"45",
"40",
"60",
"46",
"45"
),
new Question(
"What is the largest Ocean in the world?",
"Atlantic Ocean",
"Pacific Ocean",
"Indian Ocean",
"Arctic Ocean",
"Pacific Ocean"
),
new Question(
"Which one of the following is not a Marvel super-hero?",
"Spider-Man",
"Hulk",
"Batman",
"Iron Man",
"Batman"
)
];
console.log(`Bank before prompt:`, Round1Questions.map(o => o.title));
// Instead of getting the question, get the index of question
let ri = randomQuestionIndex(Round1Questions);
// Use `ri` index to splice your question array.
// Notice the `[0]` to get the first item in the returned array
let question1R1 = Round1Questions.splice(ri, 1)[0];
// No error now because `question1R1` is a `Question` class instance
question1R1.displayQuestion1R1();
console.log(`Bank after prompt:`, Round1Questions.map(o => o.title));
function randomQuestionIndex(bank){
return Math.floor(Math.random() * bank.length);
}
/* NOT RELATED TO YOUR CODE */
/* JUST TO MAKE CONSOLE MORE VISIBLE */
.as-console-wrapper { max-height: 100% !important; }
PS
Don't copy paste any answer here because your professor will immediately find out.

(ES6) Filter data with an input field (min.array)

I'm working on a website where you can search for music. I want to put a filter option where people can filter on minimum age.
This is my JSON file:
{
"artists":[
{
"name": "Martin Garrix",
"origin": "Netherlands",
"age": "22 years old",
"artist_id": "c0dc129d8a886a2c9bf487b826c3614a6630fb9c",
"best_song":"https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/98081145&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true"
},
{
"name": "Armin van Buuren",
"origin": "Netherlands",
"age": "41 years old",
"artist_id": "8b0a178ce06055312456cccc0c9aa7679d8054f1",
"best_song":"https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/181749728&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true"
},
{
"name": "Don Diablo",
"origin": "Netherlands",
"age": "38 years old",
"artist_id": "178c6e7e3bf24710d4895048586a86f1bb81d842",
"best_song":"https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/212802517&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true"
},
{
"name": "David Guetta",
"origin": "France",
"age": "50 years old",
"artist_id": "c2714423228a8012ad37af0186447cbb7ff589f7",
"best_song":"https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/140006470&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true"
},
{
"name": "Alesso",
"origin": "Sweden",
"age": "26 years old",
"artist_id": "69fa09f6e181093fe0ea2ce1a4099066509f7837",
"best_song":"https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/288914798&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true"
}
]
}
And this is my HTML:
<div class = "div-age">
<label for="age-select">Minimum age</label>
<input type="text" class = "search-age">
</div>
So for example; If you put 40 in the input field, you only get "Armin van Buuren" and "David Guetta".
This is what I have right now.
document.querySelector(`.search-age`).addEventListener(`keyup` , e => {
const term = e.target.value.toLowerCase();
const ageList = document.getElementsByClassName(`artist-info`);
Array.from(ageList).forEach(function(ageList) {
const artistAge = ageList.querySelector(`.age`).textContent;
if (artistAge.toLowerCase().includes(term)) {
ageList.style.display = `flex`;
} else {
ageList.style.display = `none`;
}
})
});
The problem I have now, is that it only filter the exact number. So for example, I put 22, I only get "Martin Garrix"
with filter(), you can do the following way:
const input = {
artists: [
{
name: 'Martin Garrix',
origin: 'Netherlands',
age: '22 years old',
artist_id: 'c0dc129d8a886a2c9bf487b826c3614a6630fb9c',
best_song:
'https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/98081145&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true',
},
{
name: 'Armin van Buuren',
origin: 'Netherlands',
age: '41 years old',
artist_id: '8b0a178ce06055312456cccc0c9aa7679d8054f1',
best_song:
'https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/181749728&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true',
},
{
name: 'Don Diablo',
origin: 'Netherlands',
age: '38 years old',
artist_id: '178c6e7e3bf24710d4895048586a86f1bb81d842',
best_song:
'https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/212802517&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true',
},
{
name: 'David Guetta',
origin: 'France',
age: '50 years old',
artist_id: 'c2714423228a8012ad37af0186447cbb7ff589f7',
best_song:
'https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/140006470&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true',
},
{
name: 'Alesso',
origin: 'Sweden',
age: '26 years old',
artist_id: '69fa09f6e181093fe0ea2ce1a4099066509f7837',
best_song:
'https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/288914798&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true',
},
],
};
const minAge = 40;
const output = input.artists.filter(cur => minAge < parseInt(cur.age));
console.log(output);
You may try to convert the age string to corresponding number using parseInt and then compare it to the value:
// Convert term and artist's age to corresponding integers
term = parseInt(term, 10);
artistAge = parseInt(artistAge, 10);
if (artistAge >= term) {
ageList.style.display = `flex`;
} else {
// ...
}
A couple of things:
you don't need Template literals, you can just use plain string.
Don't use keyup, use input instead as event for such things: it also get things if the user paste the value using a different device than keyboard – e.g. mouse.
Don't use getElementsByClassName since it returns a live HTMLCollection. Use querySelectorAll instead, that returns a static NodeList. It also supports forEach directly, so you don't need to use Array.from.
Don't shadowing the variable, as ageList in the code you wrote, for example: it can lead to unexpected bugs.
Said that:
// you might not want to query all the time this list,
// every time the user change the input value.
const ageList = document.querySelectorAll('.artist-info');
document.querySelector('.search-age').addEventListener('input' , e => {
// no need to lowercase, it's numeric.
// you might want to add some check or constraint on
// <input> validation
const term = +e.target.value;
ageList.forEach(node => {
const artistAge = node.querySelector('.age').textContent;
node.style.display = parseInt(artistAge, 10) >= term ? 'flex' : 'none';
})
});

unable to access object property through bracket variable notation

I am attempting to access one of the object propertie through a bracket notation, but I can not figure out why it is not working. As always, Your help is greatly appreciated!
js:
var dude = [
{
question1: "What is dude's favourite food?",
choices1: ["Pizza", "Pasta", "Chips", "Ice cream"],
answer1: 1
},
{
question2: "What was dude's first ever job?",
choices2: ["Staples", "Vodafone", "Costa", "Post office"],
answer2: 0
},
]
var counter = 1;
var currentQues = "question"+counter;
console.log(dude[currentQues]);
The console returns "undefined". Is this because it can not access a property through a variable(currentQues), which essentially holds another variable(counter)?
As always, your help is greatly appreciated. I am just a beginner looking to advance.
dude refers to an array of objects. You're trying to access question1 on dude, but you need to access it on dude[0]:
console.log(dude[0][currentQues]);
// -------------^^^
Live Example:
var dude = [
{
question1: "What is dude's favourite food?",
choices1: ["Pizza", "Pasta", "Chips", "Ice cream"],
answer1: 1
},
{
question2: "What was dude's first ever job?",
choices2: ["Staples", "Vodafone", "Costa", "Post office"],
answer2: 0
},
]
var counter = 1;
var currentQues = "question"+counter;
console.log(dude[0][currentQues]);
I would strongly recommend reconsidering that data structure. The names of the properties of the objects should be the same for all the objects, with just their position in the array differentiating them:
var dude = [{
question: "What is dude's favourite food?",
choices: ["Pizza", "Pasta", "Chips", "Ice cream"],
answer: 1
},
{
question: "What was dude's first ever job?",
choices: ["Staples", "Vodafone", "Costa", "Post office"],
answer: 0
},
]
dude.forEach(function(entry, index) {
var num = index + 1;
console.log("Question #" + num + ": " + entry.question);
});
You need to take the index of the array as well.
var dude = [{ question1: "What is dude's favourite food?", choices1: ["Pizza", "Pasta", "Chips", "Ice cream"], answer1: 1 }, { question2: "What was dude's first ever job?", choices2: ["Staples", "Vodafone", "Costa", "Post office"], answer2: 0 }],
counter = 1;
currentQues = "question" + counter;
console.log(dude[counter - 1][currentQues]);
// ^^^^^^^^^^^

How to generate a random name with a preceding nametag in Screeps?

In the Programming Game Screeps I spawn creeps by using:
if(transporters.length < 0 && harvesters.length > 2) {
var newName = Game.spawns['SpawnZone'].createCreep([WORK,CARRY,MOVE], undefined, {role: 'transporter'});
console.log('Spawning new Transporter: ' + newName);
}
The 'undefined' tag is to spawn the creep with a random name. Now I'm wondering since I got different types of creeps if I can add a roletag infront of it? Like, for example, [Transporter] RandomName.
Is that possible?
I found that just naming with their job and the current game time fills the need well.
ex: "Builder" + Game.time.toString() = Builder1234
A spawn can only make one creep at a time, so the name should always be unique.
Only issue is if 2+ spawners try to make a bot at the same time (same tick), whomever didn't start the spawn first will fail with with ERR_NAME_EXISTS, but you could just get them on your next cycle.
You could implement a function that will generate the name in the format you want and replace undefined with the generated name. From Screeps documentation:
createCreep(body, [name], [memory])
Start the creep spawning process. The required energy amount can be
withdrawn from all spawns and extensions in the room.
[...]
name (optional) string
The name of a new creep. It should be unique
creep name, i.e. the Game.creeps object should not contain another
creep with the same name (hash key). If not defined, a random name
will be generated.
The Screeps Forum actually already has a solution for what you need. Transcript below:
var names1 = ["Jackson", "Aiden", "Liam", "Lucas", "Noah", "Mason", "Jayden", "Ethan", "Jacob", "Jack", "Caden", "Logan", "Benjamin", "Michael", "Caleb", "Ryan", "Alexander", "Elijah", "James", "William", "Oliver", "Connor", "Matthew", "Daniel", "Luke", "Brayden", "Jayce", "Henry", "Carter", "Dylan", "Gabriel", "Joshua", "Nicholas", "Isaac", "Owen", "Nathan", "Grayson", "Eli", "Landon", "Andrew", "Max", "Samuel", "Gavin", "Wyatt", "Christian", "Hunter", "Cameron", "Evan", "Charlie", "David", "Sebastian", "Joseph", "Dominic", "Anthony", "Colton", "John", "Tyler", "Zachary", "Thomas", "Julian", "Levi", "Adam", "Isaiah", "Alex", "Aaron", "Parker", "Cooper", "Miles", "Chase", "Muhammad", "Christopher", "Blake", "Austin", "Jordan", "Leo", "Jonathan", "Adrian", "Colin", "Hudson", "Ian", "Xavier", "Camden", "Tristan", "Carson", "Jason", "Nolan", "Riley", "Lincoln", "Brody", "Bentley", "Nathaniel", "Josiah", "Declan", "Jake", "Asher", "Jeremiah", "Cole", "Mateo", "Micah", "Elliot"]
var names2 = ["Sophia", "Emma", "Olivia", "Isabella", "Mia", "Ava", "Lily", "Zoe", "Emily", "Chloe", "Layla", "Madison", "Madelyn", "Abigail", "Aubrey", "Charlotte", "Amelia", "Ella", "Kaylee", "Avery", "Aaliyah", "Hailey", "Hannah", "Addison", "Riley", "Harper", "Aria", "Arianna", "Mackenzie", "Lila", "Evelyn", "Adalyn", "Grace", "Brooklyn", "Ellie", "Anna", "Kaitlyn", "Isabelle", "Sophie", "Scarlett", "Natalie", "Leah", "Sarah", "Nora", "Mila", "Elizabeth", "Lillian", "Kylie", "Audrey", "Lucy", "Maya", "Annabelle", "Makayla", "Gabriella", "Elena", "Victoria", "Claire", "Savannah", "Peyton", "Maria", "Alaina", "Kennedy", "Stella", "Liliana", "Allison", "Samantha", "Keira", "Alyssa", "Reagan", "Molly", "Alexandra", "Violet", "Charlie", "Julia", "Sadie", "Ruby", "Eva", "Alice", "Eliana", "Taylor", "Callie", "Penelope", "Camilla", "Bailey", "Kaelyn", "Alexis", "Kayla", "Katherine", "Sydney", "Lauren", "Jasmine", "London", "Bella", "Adeline", "Caroline", "Vivian", "Juliana", "Gianna", "Skyler", "Jordyn"]
Creep.getRandomName = function(prefix){
var name, isNameTaken, tries = 0;
do {
var nameArray = Math.random() > .5 ? names1 : names2;
name = nameArray[Math.floor(Math.random() * nameArray.length)];
if (tries > 3){
name += nameArray[Math.floor(Math.random() * nameArray.length)];
}
tries++;
isNameTaken = Game.creeps[name] !== undefined;
} while (isNameTaken);
return prefix+" "+name;
}
Similar to #Matthew-Regul I just gave them a random serial number attached to their duty :
'UPGRADER_' + (Math.floor(Math.random() * 65534) + 1)
Although his removes the extremely slight possibility of repeated names
I found that the default naming scheme in screeps is lacking because the name doesn't say much about the role of creeps. For this I wrote a small utility class called util.nameBuilder.
It uses Memory.nameIndex = {}; to keep track of the number of times a prefix has been assigned to a creep. Because I don't want to randomly increase the count if the spawning of a creep failed I have a getName(role) and a commitName(role). getName() returns a name for use and commitName() will increase the count by 1. You might want to 'fold' the count if it goes above a certain threshold(say 1000) to prevent names like harvester243874. My spawn method will actually call commitName(role) if createCreep() returns a 'name already in use' error.
The result of this code are names like:
harvester1, builder23, upgrader5
var nameBuilder = {
getName: function(role) {
if (Memory.nameIndex === undefined)
Memory.nameIndex = {};
if (Memory.nameIndex[role] === undefined)
Memory.nameIndex[role] = 0;
return role + (Memory.nameIndex[role] + 1);
},
commitName: function(role) {
var newIndex = Memory.nameIndex[role] + 1;
Memory.nameIndex[role] = newIndex;
}
};
module.exports = nameBuilder;
"Upgrader_" + spawn.name + "_" + Game.time
Creates a garanteed unique name.

I'm trying to generate an array but the same id tags are breaking the html - javascript

I have been struggling with this all day. Before I learn how to make this dynamic I want to generate multiple divs with either difference id tags or classnames instead of ids. Whichever is easier. Currently I have an issue where my page spits out an array where each div has the same id. Please advise.
function byId(id) {
return document.getElementById(id);
}
var txt = {
"characters": [{
"thumbn": "<img src=\"http:\/\/galnova.com\/nu_images\/tiled.jpg\"\/>",
"fullName": "John Doe",
"speci": "human male",
"occup": "Web Personality",
"cide": "Sleeper",
"descr": "blah",
"biog": "blarg",
"allia": "chaos good",
"fullon": "<img src=\"http:\/\/galnova.com\/nu_images\/ban_two.jpg\"\/>"
},
{
"thumbn": "<img src=\"http://galnova.com/nu_images/tiled.jpg\"/>",
"fullName": "Jane Doe",
"speci": "human female",
"occup": "Movie Producer",
"cide": "Citric",
"descr": "bluh",
"biog": "blurg",
"allia": "neutral",
"fullon": "<img src=\"http:\/\/galnova.com\/nu_images\/tiled.jpg\"\/>"
},
{
"thumbn": "<img src=\"http://galnova.com/nu_images/tiled.jpg\"/>",
"fullName": "Canter Doma",
"speci": "alienmale",
"occup": "Chef",
"cide": "Galv",
"descr": "bleh",
"biog": "blerg",
"allia": "evil",
"fullon": "<img src=\"http:\/\/galnova.com\/nu_images\/tiled.jpg\"\/>"
}]
};
var obj = txt;
//obj.toString();
byId("thumb").innerHTML = obj.characters[0,1,2].thumbn;
byId("fname").innerHTML = obj.characters[0,1,2].fullName;
byId("spec").innerHTML = obj.characters[0,1,2].speci;
byId("occu").innerHTML = obj.characters[0,1,2].occup;
byId("cid").innerHTML = obj.characters[0,1,2].cide;
byId("desc").innerHTML = obj.characters[0,1,2].descr;
byId("bio").innerHTML = obj.characters[0,1,2].biog;
byId("alli").innerHTML = obj.characters[0,1,2].allia;
byId("char").innerHTML = obj.characters[0,1,2].fullon;
http://jsfiddle.net/mn9LV/8/
Not 100% sure what you're trying to do, but at a quick glance, you probably aren't referencing the array of characters as you intended :
obj.characters[0,1,2].thumbn;
Will always give you the 3rd item in the array as your usage of the , (comma) operator in this case will always result in the value passed as 2.
If you want item 1 , obj.characters[0], item 2 obj.characters[1], etc.
To expand, the the returned value of a series of commas in javascript will be the last evaluation. ie : ('a',1020,'dog') will evaluate to 'dog'. (10,20,30) == 30 // true
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator
Your array doesn't work like that
The structure you have is {[{},{},{}]}, this means
object { array [ object {}, object {}, object {} ] }
What you wrote isn't simply possible using json and javascript
Instead try
// John Doe
byId("thumb").innerHTML = obj.characters[0].thumbn;
byId("fname").innerHTML = obj.characters[0].fullName;
byId("spec").innerHTML = obj.characters[0].speci;
byId("occu").innerHTML = obj.characters[0].occup;
byId("cid").innerHTML = obj.characters[0].cide;
byId("desc").innerHTML = obj.characters[0].descr;
byId("bio").innerHTML = obj.characters[0].biog;
byId("alli").innerHTML = obj.characters[0].allia;
byId("char").innerHTML = obj.characters[0].fullon;
Next is 1
// Jane Doe
byId("thumb").innerHTML = obj.characters[1].thumbn;
byId("fname").innerHTML = obj.characters[1].fullName;
byId("spec").innerHTML = obj.characters[1].speci;
byId("occu").innerHTML = obj.characters[1].occup;
byId("cid").innerHTML = obj.characters[1].cide;
byId("desc").innerHTML = obj.characters[1].descr;
byId("bio").innerHTML = obj.characters[1].biog;
byId("alli").innerHTML = obj.characters[1].allia;
byId("char").innerHTML = obj.characters[1].fullon;
== Edit ==
To better suit your needs based on commenting this may suffice
Enclose your object in a literal and build in the functions you need to filter or build html in the literal
var obj = {
txt: {
"characters": [{
"thumbn": "<img src=\"http:\/\/galnova.com\/nu_images\/tiled.jpg\"\/>",
"fullName": "John Doe",
"speci": "human male",
"occup": "Web Personality",
"cide": "Sleeper",
"descr": "blah",
"biog": "blarg",
"allia": "chaos good",
"fullon": "<img src=\"http:\/\/galnova.com\/nu_images\/ban_two.jpg\"\/>"
},
{
"thumbn": "<img src=\"http://galnova.com/nu_images/tiled.jpg\"/>",
"fullName": "Jane Doe",
"speci": "human female",
"occup": "Movie Producer",
"cide": "Citric",
"descr": "bluh",
"biog": "blurg",
"allia": "neutral",
"fullon": "<img src=\"http:\/\/galnova.com\/nu_images\/tiled.jpg\"\/>"
},
{
"thumbn": "<img src=\"http://galnova.com/nu_images/tiled.jpg\"/>",
"fullName": "Canter Doma",
"speci": "alienmale",
"occup": "Chef",
"cide": "Galv",
"descr": "bleh",
"biog": "blerg",
"allia": "evil",
"fullon": "<img src=\"http:\/\/galnova.com\/nu_images\/tiled.jpg\"\/>"
}]
},
byId: function(id) {
return document.getElementById(id);
},
buildHtml: function(id) {
this.byId("thumb").innerHTML = this.txt.characters[id].thumbn;
this.byId("fname").innerHTML = this.txt.characters[id].fullName;
this.byId("spec").innerHTML = this.txt.characters[id].speci;
this.byId("occu").innerHTML = this.txt.characters[id].occup;
this.byId("cid").innerHTML = this.txt.characters[id].cide;
this.byId("desc").innerHTML = this.txt.characters[id].descr;
this.byId("bio").innerHTML = this.txt.characters[id].biog;
this.byId("alli").innerHTML = this.txt.characters[id].allia;
this.byId("char").innerHTML = this.txt.characters[id].fullon;
}
};
Usage
var objectById = obj.byId(0);
// Or build html
obj.buildHtml(1);

Categories