How to create an array of json containing 100 json objects in javascript using for loop with properties id and name. Use Math.random() to create random ids. The random number should be between 1-100. E.g. [{id:1,"name":"lorem"},{id:2,"name":"ipsum"}....]
Asked
Active
Viewed 1,032 times
-3
-
1Post code that you have tried otherwise you will more than likely get no help. – Ryan Wilson Mar 15 '18 at 14:31
-
Actually i am not getting idea where to start from. Please help me. – Klaus Mar 15 '18 at 14:39
-
Read these: [for loop](https://stackoverflow.com/questions/52080/how-do-i-build-a-loop-in-javascript), [random number](https://stackoverflow.com/questions/1527803/generating-random-whole-numbers-in-javascript-in-a-specific-range), [random string](https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript) – gforce301 Mar 15 '18 at 14:43
1 Answers
1
var out = new Array(100).fill(1).map(function(val, index){
return {
"name": "Name number: " + index,
"id": Math.floor((Math.random() * 100) + 1)
}
});
console.log(out);
~or~
var out = [];
for(var i = 0; i < 100; i++){
out.push({
"name": "Name number: " + i,
"id": Math.floor((Math.random() * 100) + 1)
});
};
console.log(out);

Stucco
- 388
- 5
- 21