簡體   English   中英

獲取數組 Json 的一個 object

[英]Get one object of array Json

我按照這個小如何在nodejs中應用一個簡單的api。 這不是我的專業領域,我是一名計算機網絡分析師,雖然我在 C ++(簡單)和 C # 中開發應用程序,但我對如何獲得以下代碼返回的數組的結果有一點疑問:

Javascript 代碼使用 Mysql ->

//
 exports.findAll = (req, res) => {
 const name = req.query.name;
 var condition = name ? { name: { [Op.like]: `%${name}%` } } : null;

Custumers.findAll({ where: condition })
.then(data => {
    res.send(data);;
})
.catch(err => {
  res.status(500).send({
    message:


      err.message || "Some error occurred while retrieving name."
   });
 });
};

訪問 URL 以檢查一切是否按預期進行。

http://10.1.1.254:8085/api/custumers?name=Gabriel

我的結果:

  [
   {"id":6,
   "name":"Gabriel",
   "cod":10,
   "igCustumer":"1",
   "createdAt":null,
   "updatedAt":null}
   ]

我怎樣才能得到名稱、鱈魚、imgCustumer 的值?

我試試;

axios.get(`http://10.1.1.254:8085/api/custumers?name=Gabriel`).then((res) => {
let myvar = `My result:\n\n${res.data.name}`;
console.log(myvar);
})

如果結果:未定義

您可以像這樣訪問 JavaScript 中的 object 值...

let res =   [{"id":6,
   "name":"Gabriel",
   "cod":10,
   "igCustumer":"1",
   "createdAt":null,
   "updatedAt":null}]

let name = res[0].name;
let cod = res[0].cod;
let igCustomer = res[0].igCustumer;

因為res是一個充滿對象的數組,所以您可以訪問 object 及其在索引中的位置,例如res[0] 從那里您可以使用點符號或括號 select object 中的鍵/值對。 每種方法都有其用途。

嘗試這樣的事情:

let res = [
   {"id":6,
   "name":"Gabriel",
   "cod":10,
   "igCustumer":"1",
   "createdAt":null,
   "updatedAt":null}
   ]

console.log(res[0]['name']);
console.log(res[0]['cod']);
console.log(res[0]['igCustumer']);

您嘗試訪問不存在的字段的代碼問題。 res.data將等於您的端點的響應。 您的響應是一個數組,因此顯然它沒有name字段。 所以你需要拿一個特定的object。

const user = res.data[0]; // Taking the first user.

然后您可以訪問其數據。

user.name; // Gabriel

要從數組中查找數據,您可以迭代該數組並像這樣使用 find:

 let res = [ {id:6, name:"Gabriel", cod:10, igCustumer:"1", createdAt:null, updatedAt:null} ] let myVar = res.find((item) => { return item.name === 'Gabriel' }); console.log(myVar.name); console.log(myVar.cod); console.log(myVar.igCustumer);

暫無
暫無

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

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