簡體   English   中英

將數組值作為參數傳遞給 function 並創建 json 數據

[英]Pass array values as parameter to function and create json data

我有一個場景,我將一個對象數組傳遞給 nodejs 中的 function,但同樣失敗並出現未定義的錯誤。

這是我嘗試過的:

 var object = issues.issues //json data
 var outarr=[];
 for(var key in object){
   outarr.push(object[key].key) 
}
console.log(outarr) // array is formed like this : ['a','b','c','d','e']

for(var i =0; i<outarr.length;i++){  
jira.findIssue(outarr[i]) //here I am trying to pass the array objects into the loop one by one 
  .then(function(issue) {
    var issue_number = issue.key
    var ape = issue.fields.customfield_11442[0].value
    var description = issue.fields.summary
    var ice = issue.fields.customfield_15890[0].value
    var vice = issue.fields.customfield_15891.value
    var sor = issue.fields.labels
    if (sor.indexOf("testcng") > -1) {
      var val = 'yes'
} else {
  var val = 'yes'
}
var obj = {};
obj['ape_n'] = ape;
obj['description_n'] = description;
obj['ice_n'] = ice;
obj['vice_n'] = vice;
obj['sor_n'] = val;

var out = {}
var key = item;
out[key] = [];
out[key].push(obj);

console.log(out)
 } })
  .catch(function(err) {
    console.error(err);
  });


});

我想要實現的目標:我想將數組值作為jira.findissue所需的參數(基本上傳遞問題編號)一個一個地傳遞,並且應該再次獲取這些值並給出組合 json output。 如何在此 function 中一一傳遞此數組值,並在循環中運行jira.findissue

任何幫助都會很棒:! :-)

我已經查看了您問題中的代碼。 老實說,您編寫的代碼很混亂,並且包含一些簡單的語法錯誤。

一個好的提示是使用 linter 來避免這些錯誤。 更多關於 linters 的信息: https://www.codereadability.com/what-are-javascript-linters/

對於 output 所有結果都在一個數組中,您必須在循環的 scope 之外定義數組。

我稍微清理了代碼並使用了一些 es6 功能。 我不知道代碼的上下文,但這是我可以做到的:

//map every value the key to outarr
let outarr = issues.issues.map( elm => elm.key);

//Output defined outside the scope of the loop
let output = [];

//looping outarr
outarr.forEach( el => {
    jira.findIssue(el).then(issue => {
        //creating the issue object
        let obj = {
            ape_n: issue.fields.customfield_11442[0].value,
            description_n: issue.fields.summary,
            ice_n: issue.fields.customfield_15890[0].value,
            vice_n: issue.fields.customfield_15891.value,
            sor_n: issue.fields.labels.indexOf("testcng") > -1 ? "yes" : "yes",
        };
        //pushing to the output
        output[issue.key] = obj;
    }).catch(err => {
        console.log(err);
    });
});

//ouputing the output
console.log(output);

有關 es6 功能的更多信息: https://webapplog.com/es6/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM