Home > Enterprise >  Generating a random array of objects (randomic profile persons)
Generating a random array of objects (randomic profile persons)

Time:01-28

Generate an array with 10 objects of this type: { name: "Person X", (where instead of X you will put a progressive number) sex: < "M" or "F" > , (should be random) age: < number between 18 and 100) }

The result should be something like this:

[{
        "Name": "Person 1",
        "sex": "F",
        "eta": 22
    },
    {
        "Name": "Person 2",
        "sex": "F",
        "eta": 56
    },
    {
        "Name": "Person 3",
        "sex": "M",
        "eta": 33
    },
    ...
]

need to use "for"loop and Math.random to generate randomers

CodePudding user response:

Here's your solution. The following code generates 10 people with a name, sex, and eta and appends it to the people array using a for loop and Math.random.

let people = [];
for (var i = 0; i < 10; i  ) {
    people.push(person = {
        Name: "Person "   (i 1),
        sex: Math.round(Math.random()) ? "M" : "F",
        eta: Math.floor((Math.random() * (100 - 18)   18))
    });
}
  •  Tags:  
  • Related