在 Nodejs 中循环 json 数组时为空数组

Empty array when looping json array in Nodejs

我想从 adonisjs 中的 JSON 数组中获取特定数据。但是我在获取该数据时遇到了一些问题。当我循环此 JSON 数组时,return 只是 empty 数组 = []。这是我的控制器代码:

   const detail= await TrxHistory.query()
        .where('id_trx', params.id_trx)
        .fetch()

这个returnjson数组:

[
    {
        "id_trx_history": "1",
        "id_trx": "3",
        "trx_status": "shop_confirm",
        "created_at": "2019-10-18 22:27:54"
    },
    {
        "id_trx_history": "1",
        "id_trx": "3",
        "trx_status": "shop_process",
        "created_at": "2019-10-18 22:29:48"
    },
]

我尝试从行 "trx_status" 中获取数据,使用这样的循环:

        let data = [];
        for(var i = 0; i < detail.length; i++) {
            data[i] = detail[i]["trx_status"];
        }
        console.log(data);

这段代码有什么问题?

如果 detail 具有您展示的结构,那么它应该可以完美运行:

const detail = [
{
    "id_trx_history": "1",
    "id_trx": "3",
    "trx_status": "shop_confirm",
    "created_at": "2019-10-18 22:27:54"
},
{
    "id_trx_history": "1",
    "id_trx": "3",
    "trx_status": "shop_process",
    "created_at": "2019-10-18 22:29:48"
},
];

let data = [];
for (let i = 0; i < detail.length; i++) {
     data[i] = detail[i]["trx_status"];
}
console.log(data);

// another way:
let fooData = [];
detail.forEach(el => {
    el["trx_status"] ? fooData.push(el["trx_status"]) : null;
});
console.log(fooData);

当您fetch adonis lucid 请求时您需要使用.rows。喜欢:

... // Your query

let fooData = [];
detail.rows.forEach(de => {
    fooData.push(el.trx_status)
})

如何使用?

detail.rows[1]
detail.rows.length