0

I wanted objects like this:

  [{ age: 3, area: 5 }, 
   { age: 4, area: 15 }, 
   { age: 19, area: 3 }, 
   { age: 16, area: 11 }, 
   { age: 20, area: 4 }, 
   { age: 6, area: 9 }]

The approach was to create new objects each time and push it inside an array.

  function Numstuff(age,area) {
      this.age = age,
      this.area = area
  }

  var numObjArray = []

var createObj = new Numstuff (Math.floor(Math.random() * 20), 
Math.floor(Math.random() * 20))



numObjArray.push(createObj)

But This pushes only one. How to create multiple objects and push inside an array?

2
  • If you're sure you're never going to use the NumStuff constructor without wanting the new object added to the array, you can put numObjArray.push(this) at the end of the constructor. Commented Oct 30, 2018 at 19:51
  • Or, if all values will be generated the same way, just use a loop Commented Oct 30, 2018 at 19:52

3 Answers 3

1

You can make an array directly with Array.from() and fill it with your objects by passing a function:

function Numstuff(age,area) {
    this.age = age,
    this.area = area
}

// make 10 numstuffs
const num = 10
let arr = Array.from({length: num}, () => new Numstuff (Math.floor(Math.random() * 20), Math.floor(Math.random() * 20)))

console.log(arr)

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

Comments

1

What about this:

var array = [];
var obj = {};

for(var i=0;i<=10;i++){
  
  obj = {age: i, area: Math.random()}
  array.push(obj);
}

console.log(array)

3 Comments

Why are you creating all the extra empty objects?
@MarkMeyer are you talking about obj ?
Yes, let obj = {age: i, area: Math.random()} in the loop is enough. You don't need the other obj = {}
0

Maybe with a for loop. Using you own code:

for (var i = 0; i < 9; i++) {
    var createObj = new Numstuff (Math.floor(Math.random() * 20), 
    Math.floor(Math.random() * 20))
    numObjArray.push(createObj)
}

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.