MayaGans
MayaGans

Reputation: 1845

Pushing objects into array using forEach

I have an on click event that changes the values of three elements that I want to combine into a json-like object:

function generateNumbers() {
  let a = Math.random()
  let b = Math.random()
  let c = Math.random()
  console.log({
    "numbers": [
      {"a": a, "b": b, "c": c}
    ]
  })
}
<button onclick="generateNumbers()">Three Numbers</button>

Rather than replace a, b, and c I want to add another object {"a": a, "b": b, "c": c} with each click. Is this possible?

Desired Output

{
  "numbers": [
    {
      "a": 0.795741457922079,
      "b": 0.07941685760724382,
      "c": 0.048012832026655516
    },
    {
      "a": 0.17600389141580575,
      "b": 0.4720288949307833,
      "c": 0.8079844242898715
    },
  ]
}

Upvotes: 1

Views: 496

Answers (3)

AhsanBilal
AhsanBilal

Reputation: 121

you need to define your object outside of function and push the new value set in numbers through generateNumbers

const data = { numbers: [] }

function generateNumbers(){
  const val = Math.random;
  data.numbers.push({ a: val(), b: val(), c: val() )})
}

Upvotes: 0

norbitrial
norbitrial

Reputation: 15166

You need to create an initial object which contains the numbers property as array where you can push the newly generated object with a, b and c properties. Read about .push():

The push() method adds one or more elements to the end of an array and returns the new length of the array.

Try as the following:

const data = {
   numbers: []
};

function generateNumbers() {
  let a = Math.random()
  let b = Math.random()
  let c = Math.random()
  
  data.numbers.push({"a": a, "b": b, "c": c});
  
  console.log(data);
}
<button onclick="generateNumbers()">Three Numbers</button>

I hope this helps!

Upvotes: 1

twharmon
twharmon

Reputation: 4282

You need to add a variable for the numbers outside of the generateNumbers function.

const state = { numbers: [] }

function generateNumbers() {
  let a = Math.random()
  let b = Math.random()
  let c = Math.random()
  
  state.numbers.push({ a, b, c })

  console.log(state)
}
<button onclick="generateNumbers()">Three Numbers</button>

Upvotes: 0

Related Questions