0

I need some dummy data that I can use. I usually, manually create my data in a variable like...

const jsonData = [
  {
    name: 'random',
    age: '0',
  }
];

I'm trying to create a function that gives me back an array with a list of objects in (like the above) the amount of objects in the array is based on the value I give it.

I came to the conclusion using the map function would be best, like so:

const myMap = new Map();

myMap.forEach((q, n) => {

});

I'm still learning. Honestly now sure how I'd go about creating this.

2

1 Answer 1

3

You can use a simple loop:

function genData(n) {
  var results = [];
  for (var i = 0; i < n; i++) {
    results.push({name: 'random', age: 0});
  }
  return results;
}

If you want to randomize the property values, look into Math.random.


Here is a simple example that picks a random value from provided lists:

function genData(n, values) {
  var results = [];
  for (var i = 0; i < n; i++) {
    var obj = {};
    for (var prop in values) {
      obj[prop] = values[prop][Math.floor(Math.random() * values[prop].length)];
      results.push(obj);
    }
  }
  return results;
}

console.log(genData(3, {name: ['foo', 'bar', 'baz'], age: [0, 10, 20, 30, 40]}));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.