如何获得JSON数组中的最后一个索引,当你不知道数组将会有多大? [英] How to get the last index in a JSON array when you don't know how large the array is going to be?

查看:297
本文介绍了如何获得JSON数组中的最后一个索引,当你不知道数组将会有多大?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON对象的数组。这个数组在for循环中,并且随着信息从数据库中获取,它不断地将它们添加到数组中。数组中的对象数量可能与数据库返回的结果数量不同(因为只有一些位置可能有用户正在搜索的食物类型)。例如,我可以在 rows 中返回12家餐馆,但是只有3家卖汉堡,所以我可以 t只是做 if(rows.length - 1 == i),因为 i 只会达到2 rows.length - 1 是11.

所以匹配的返回结果(JSON)被逐个添加一个for循环。我永远不能先知地知道有多少餐馆卖汉堡,直到所有这些餐馆都加入了这个餐馆。

我尝试了各种各样的技巧,从节点得到的错误是不能多次发送头文件。我知道为什么它给了我这个错误。它给了我这个错误,因为循环的每一次迭代它将返回它在数组中的所有内容。



输出的例子

第一次迭代:

<
$ {code $ {results:[{name_of_restaurant:joes burgers,open_now:true}]}

b

第二个迭代:
$ b $ p结果{[name_of_restaurant:joes burgers,open_now:true} ,{name_of_restaurant:five guys,open_now:true}]}
$ b

第三次迭代:

结果:{{name_of_restaurant:joes burgers,open_now:true},{name_of_restaurant:five guys,open_now :true},
{name_of_restaurant:shake shack,open_now:true}]
}



为了说清楚,我不是在寻找 array.length - 1 。我的问题要复杂得多。

编辑 - 添加了代码

 函数retrieveLocation(callback){
var locationsWithinVisibleMapRectQuery =SELECT * FROM locations WHERE Y(coordinates)>+ req.body.SWCoordLat +AND Y(coordinates) ANDX(coordinates)>+ req.body.SWCoordLong +AND X(coordinates)" + req.body.NECoordLong +;;
connection.query(locationsWithinVisibleMapRectQuery,function(err,rows){
if(err)throw err;

var jsonObject = {
results:[]
$;

//console.log(\"企业数量:+ rows.length);

for(var i = 0; i< (business.number);
var businessName = rows [i] .name;
console.log(businessName );
console.log();
var x = rows [i] .coordinates.x;
var y = rows [i] .coordinates.y;

getMenuForEachLocation(x,y,businessName,rows,i,function(err,obj){

if(err){
callback(err,null);
}

jsonObject [results]。push(obj);

if(jsonObject [results] ==最后一个索引)上次迭代n作为回应发回
callback(null,jsonObject);
}
});
}
});

$ b $ retrieve $(b





$ b $ $ b});


解决方案

检查<$ 结果等于 .length .length code> rows 数组。注意,由于结果是异步填充的,所以得到的数组可能不是按照 i

$ b的顺序
$ b

  var rows = [0,1,2,3,4,5,6],results = [],asyncFn = function(n){return new Promise函数(解析){setTimeout(函数(){解析(n)},Math.random()* 3000)}),完整=函数(回调){for(var i = 0; i< rows.length; (结果); if(results.length === rows.length)callback(rows,results)})} complete(//`callback`:做结果时``.length`等于`rows``.length`函数(rows_,results_){console.log(rows_,results_)alert(complete) ;});  


I have an array of JSON objects. This array is within a for loop and it keeps adding them to the array as the information becomes available from the database. The number of the objects in the array might not be the same as the number of results returned from the database (because only some locations might have the type of food a user is searching for).

For instance, I can have 12 restaurants returned in rows, however only 3 sell hamburgers, so I can't simply do if (rows.length - 1 == i), because i is only going to reach 2 while rows.length - 1 is 11.

So the matching returned results (JSON) are added one by one in a for loop. I can never preemptively know how many restaurants sell burgers until all those restaurants that do are added to the array.

I've tried a variety of tricks and the usual error I get from node is "can't send headers more than once." And I know why it's giving me this error. It's giving me this error because every iteration of the loop it will return whatever it has in the array.

An example of output

First iteration:

{ "results": [ {"name_of_restaurant": "joes burgers", "open_now": true }] }

Second iteration:

{ "results": [ {"name_of_restaurant": "joes burgers", "open_now": true }, { "name_of_restaurant": "five guys", "open_now": true }] }

Third iteration:

{ "results": [ { "name_of_restaurant": "joes burgers", "open_now": true }, "{ name_of_restaurant": "five guys", "open_now": true }, " { name_of_restaurant": "shake shack", "open_now": true }] }

I want a way to capture the third iteration so I can send that back to the client.

To be clear, I am not looking for array.length - 1. My problem is substantially more complex.

EDIT - code added

function retrieveLocation(callback) {
    var locationsWithinVisibleMapRectQuery = "SELECT * FROM locations WHERE Y(coordinates) > " + req.body.SWCoordLat + "AND Y(coordinates) < " + req.body.NECoordLat + "AND X(coordinates) > " + req.body.SWCoordLong + "AND X(coordinates) < " + req.body.NECoordLong + ";";
    connection.query(locationsWithinVisibleMapRectQuery, function(err, rows) {
        if (err) throw err; 

        var jsonObject = {
            "results" : []
        };

        //console.log("Number of businesses: " + rows.length);

        for(var i = 0; i < rows.length; i++) {

            console.log("Business number " + i); 
            var businessName = rows[i].name;
            console.log(businessName);
            console.log();
            var x = rows[i].coordinates.x; 
            var y = rows[i].coordinates.y; 

            getMenuForEachLocation(x, y, businessName, rows, i, function(err, obj) {

                if (err) {
                    callback(err, null); 
                }  

                jsonObject["results"].push(obj);

                if( jsonObject["results"] == the last index) { // figure a way to get last iteration to send back as a response
                     callback(null, jsonObject);  
                 }
            }); 
        }
    }); 
}

retrieveLocation(function(err, jsonObject) {
    if (err) throw err; 

    res.json(jsonObject);
});

解决方案

An working example of an approach that checks for .length of results array to be equal to .length of rows array. Note, since results is filled asynchronously, the resulting array may not be in order of i

var rows = [0, 1, 2, 3, 4, 5, 6]
  
, results = []

, asyncFn = function(n) {
  return new Promise(function(resolve) {
    setTimeout(function() {
      resolve(n)
    }, Math.random() * 3000)
  })
}

, complete = function(callback) {
  for (var i = 0; i < rows.length; i++) {
    asyncFn(i).then(function(data) {
      results.push(data);
      console.log(results);
      if (results.length === rows.length) callback(rows, results)
    })
  }
}

complete(
  // `callback` : do stuff when `results` `.length` is equal to `rows` `.length`
  function(rows_, results_) {
    console.log(rows_, results_)
    alert("complete");
  }
);

这篇关于如何获得JSON数组中的最后一个索引,当你不知道数组将会有多大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆