简体   繁体   English

遍历对象并从 Javascript 中的数组返回键值对

[英]Iterate over objects and return key-value pairs from an array in Javascript

I am trying to iterate over a JSON object and return values to another function.我正在尝试遍历 JSON 对象并将值返回给另一个函数。

在此处输入图片说明

I would like to pass each value of quadrant1_x , quadrant1_y ... quadrant4_y of its respective object to the calculatePlot() function.我想将其各自对象的quadrant1_xquadrant1_y ... quadrant4_y的每个值传递给calculatePlot()函数。 But I get an error Uncaught TypeError: user is undefined但是我收到一个错误Uncaught TypeError: user is undefined

Javascript looks like this: Javascript 看起来像这样:

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

This code is generating a cartesian plot as an SVG.此代码生成笛卡尔图作为 SVG。 So, each quadrant value of x & y is required in order to render a graph.因此,为了呈现图形,需要 x & y 的每个象限值。

Sample : JSFiddle示例: JSFiddle

Looks like you're consumeAPI method doesn't return anything.看起来您的consumeAPI方法不返回任何内容。 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...此外,将forEach循环放在for循环中并遍历相同的可迭代对象是没有意义的......

Not sure why you're iterating within the consume api.不确定为什么要在消耗 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.在 generateRandomUser 中使用循环是不合逻辑的,因为您的目标似乎是获得一个随机用户。 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.我认为所有额外的循环和诸如此类的东西都是不必要的。

Putting the return inside of a forEach will simply break out of the loop and not return anything.将 return 放在forEach只会跳出循环而不返回任何内容。 This is why consumeAPI returns undefined .这就是为什么consumeAPI返回undefined As @silencedogood mentioned, there is no need for a forEach inside of the for loop .正如@silencedogood 所提到的,在for loop不需要forEach

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.您可以使用Array.map作为替代方法,并在需要处理更多对象的情况下转换数组内的每个对象。

If graphs is an array of objects that you wish to transform, you can simply do: graphs.map(graph => {x1: graph.quadrant1_x * range ....});如果graphs是您希望转换的对象数组,您可以简单地执行: graphs.map(graph => {x1: graph.quadrant1_x * range ....}); and return the transformed array.并返回转换后的数组。

Okay, So after spending some time on basics I realized it was quite straightforward.好的,所以在花了一些基础知识之后,我意识到这很简单。

Learnings:学习:

  1. Move the incoming backend response out from consumeAPI()将传入的后端响应从 consumerAPI() 中移出
  2. Pop-out values of each object from it.从中弹出每个对象的值。
  3. Return the Object to calculatePlot() function.将对象返回给 calculatePlot() 函数。

So now the consumeAPI() looks like this.所以现在consumeAPI() 看起来像这样。

     function consumeAPI() {
            const value = sample_graphs.pop();

            const x_1 = value.quadrant1_x;
            const y_1 = value.quadrant1_y;
            const x_2 = value.quadrant2_x;
            const y_2 = value.quadrant2_y;
            const x_3 = value.quadrant3_x;
            const y_3 = value.quadrant3_y;
            const x_4 = value.quadrant4_x;
            const y_4 = value.quadrant4_y;

            let retObj = {
                x1: x_1 * range,
                y1: y_1 * range,
                x2: x_2 * range,
                y2: y_2 * range,
                x3: x_3 * range,
                y3: y_3 * range,
                x4: x_4 * range,
                y4: y_4 * range,
            };

            return retObj;
           
        }

Rest remains the same.休息保持不变。

 function generateRandomUser() {
            const user = consumeAPI();
            return calculatePlot(user);
        }
let sample_graph = [
 {
                quadrant1_x: "0.17",
                quadrant2_x: "0.53",
                quadrant3_x: "-0.48",
                quadrant4_x: "-0.86",
                quadrant1_y: "0.31",
                quadrant2_y: "-0.21",
                quadrant3_y: "-0.60",
                quadrant4_y: "0.50",
            },
    ...

];

// consumeAPI() goes here

for (let i = 0; i < maxUsers; i++) {
            let plot = generateRandomUser();
            addUser(plot);
            calculateMidPoint(plot);
        }

Sample: JSFiddle示例: JSFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM