我有一个json变量
var a = { Account: [ 'Name', 'Site', 'BillingState', 'Phone', 'Type', 'Owner.Alias' ],
联系人:['Name1','Site1']}
我正在像这样迭代循环
app.post('/', function (req, res) { a = req.body.table_structure b = createSelectQuery(a) res.send(b) // this return only "FROM CONTACT" })
我已经创建了另一个函数,希望我可以获得所需的字符串,但循环变为异步
function createSelectQuery(a){
var selectQuery = "Select "
var obj = JSON.parse(a);
for (var c in obj){
for (var d in obj[c]){
selectQuery += obj[c][d] + ', '
}
selectQuery = "FROM "+c
}
return selectQuery
}
我期待结果“来自帐户的SELECT Name,..等但是得到了 仅从帐户作为输出
答案 0 :(得分:0)
你需要使用回调来使你的循环同步
答案 1 :(得分:0)
我相信因为在JSON文件'帐户'是数组,你尝试循环到它,就好像它是一个对象。试试:
function createSelectQuery(a){
var selectQuery = "Select "
var obj = JSON.parse(a);
for (var c in obj){
for (var d=0; d < obj[c].length; d++){
selectQuery += obj[c][d] + ', '
}
selectQuery = "FROM "+c
}
return selectQuery
}
答案 2 :(得分:0)
试试这个
function createSelectQuery(a){
var selectQuery = "Select ";
var obj = JSON.parse(a);
for (var c in obj) {
selectQuery += obj[c].join(", ") + " FROM " + c;
}
return selectQuery;
}
答案 3 :(得分:0)
您可以尝试使用arr.join()连接字符串,然后使用Object.keys追加字符串,而不是循环。这样就可以了解
var selectQuery = "Select ";
var a = { Account: [ 'Name', 'Site', 'BillingState', 'Phone', 'Type', 'Owner.Alias' ]};
var obj = a;
var arr = obj['Account'];
var joinStr = arr.join(',').toString();
selectQuery = selectQuery +" "+joinStr +" FROM "+Object.keys(a);
console.log(selectQuery);