2

what I'm trying to do is to access a property inside a variable: for example I want to access the first and last name of the first user (index 0, nom and prenom) like this knowing that users are created dynamically:

I tried several solutions on the Internet, but none of them worked properly or did not match to my problem.

Source code :

var liste = new Array();
var count = liste.length;

class Personne{
    constructor(){}
    info = {
        nom: faker.name.firstName(),
        prenom: faker.name.lastName(),
        civilite: faker.address.countryCode(),
    };
}
var pers = new Personne(); //global var now
function foo() {
    faker.locale= 'fr';
    pers = new Personne();
    document.getElementById("nom-prenom").textContent = "Nom complet : " + pers.info.nom + " " + pers.info.prenom;
    document.getElementById("nationalite").textContent = "Civilité : " + pers.info.civilite;
    
    liste.push(pers.info);
    count = count + 1;
    document.getElementById("count").textContent = `Liste des utilisateurs [${count}] :`;
    console.log(liste)  
    document.getElementById("liste_util").innerHTML += `<br><button id="a${liste.length - 1}" onclick='GetPos()'>${pers.info.nom + " " + pers.info.prenom}</button>`
    return {
        compt :count, 
        personne : pers,
    };
}

function GetPos()
{
   alert(pers.info["nom"]); //here but for index 0
}

Thank you for the help.

TadasJS
  • 37
  • 5
  • Objects are not indexed. – Nora Apr 15 '21 at 20:01
  • 1
    You really want to start using template strings, all this string concatenation is one giant bug-waiting-to-happen. Also, innerHTML that adds `
    `? There is a _lot_ here that you want to post to codereview about to get some help writing better (and modern) JS.
    – Mike 'Pomax' Kamermans Apr 15 '21 at 20:05
  • 1
    It seems like you have an array of objects, so you would need something like `yourArray[0].nom` – RDU Apr 15 '21 at 20:06
  • I think you're looking for `function GetPos(i) { alert(liste[i].info.nom); }`, used as `onclick='GetPos(${count-1})'`, but what you really should do is to learn about the dom and use a closure as an event handler. Like @Mike, I suggest you post this on [codereview.SE] – Bergi Apr 15 '21 at 20:35

1 Answers1

0

Getting Object Properties by Index

Sample example that make you understand to achieve what you want:

o = { "key1": "value1", "key2": "value2"};
var idx = 1; // key2

var key = Object.keys(o)[idx];
value = o[key]

console.log(key,value); // key2 value2
Rashed Rahat
  • 2,357
  • 2
  • 18
  • 38