Home > database >  Iterate over objects and return key-value pairs from an array in Javascript
Iterate over objects and return key-value pairs from an array in Javascript

Time:11-01

I am trying to iterate over a JSON object and return values to another function.

enter image description here

I would like to pass each value of quadrant1_x, quadrant1_y...quadrant4_y of its respective object to the calculatePlot() function. But I get an error Uncaught TypeError: user is undefined

Javascript looks like this:

function generateRandomUser() {
  const user = consumeAPI()
  return calculatePlot(user)
}

function consumeAPI() {
  const graphs = @json($graphs); //received from the backend (Laravel)

  for (let i = 0; i < graphs.length; i  ) {
    graphs.forEach((value, key) => {
      console.log([key, value]);
      return {
        x1: (value.quadrant1_x * range),
        y1: (value.quadrant1_y * range),
        x2: (value.quadrant2_x * range),
        y2: (value.quadrant2_y * range),
        x3: (value.quadrant3_x * range),
        y3: (value.quadrant3_y * range),
        x4: (value.quadrant4_x * range),
        y4: (value.quadrant4_y * range),
      }
    })
  }

  function calculatePlot(user) {
    return [{
      x: center   user.x1,
      y: center - user.y1
    }, {
      x: center   user.x2,
      y: center - user.y2
    }, {
      x: center   user.x3,
      y: center - user.y3
    }, {
      x: center   user.x4,
      y: center - user.y4
    }]
  }

  for (let i = 0; i < maxUsers; i  ) {
    let plot = generateRandomUser();
    let label = `Mid-point`;
    addUser(plot, label);
    calculateMidPoint(plot);
  }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

This code is generating a cartesian plot as an SVG. So, each quadrant value of x & y is required in order to render a graph.

Sample : JSFiddle

CodePudding user response:

Looks like you're consumeAPI method doesn't return anything. So when you invoke it, the value is undefined.

Also, there is no point in putting a forEach loop inside of the for loop that iterates over the same iterable...

Not sure why you're iterating within the consume api. In fact, it's unclear why you're iterating at all.

Try returning your values:

async function consumeAPI() { // This will probably require async/await.
  const graphs = await @json($graphs); 
  return graphs;
}

Using a loop inside generateRandomUser wouldn't be logical, because it seems your goal is to get a random user. If you'd like to get a random user (item in the array), you could try something like this:

function generateRandomUser() {
   
   const users = consumeAPI()
   var randomItem = users[Math.floor(Math.random()*users.length)]

   return users[randomItem];
}

I'm thinking all the extra loops and whatnot aren't necessary.

CodePudding user response:

Putting the return inside of a forEach will simply break out of the loop and not return anything. This is why consumeAPI returns undefined. As @silencedogood mentioned, there is no need for a forEach inside of the for loop.

You can use Array.map as an alternative and transform each object inside of the array in case there are more objects that need to be handled.

If graphs is an array of objects that you wish to transform, you can simply do: graphs.map(graph => {x1: graph.quadrant1_x * range ....}); and return the transformed array.

  • Related