1

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
    },
  ]
}

3 Answers 3

1

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!

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

Comments

0

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>

Comments

0

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() )})
}

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.