第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何通過鍵從 JavaScript 字典數(shù)組中獲取對象?

如何通過鍵從 JavaScript 字典數(shù)組中獲取對象?

阿晨1998 2024-01-18 20:30:36
我希望我使用了正確的術語......我通常是一個Python人,所以我習慣了字典數(shù)據(jù)類型。不管怎樣,我現(xiàn)在正在開發(fā)一個 Node 應用程序,我遇到了一個問題。我讓用戶從下拉菜單中進行選擇,該菜單通過傳遞到 EJS 的字典對象數(shù)組進行填充。每個對象都有一個 slug 和一個名稱。所以,它會是這樣的:const computers = [{slug: 'dell-desktop', name: 'Dell Desktop'}, {slug: 'macbook-pro', name: 'MacBook Pro'}, {slug: 'imac-27-inch', name: 'iMac, 27-Inch'}];我使用名稱填充表單,但我需要后端的 URL 內容。所以它看起來像這樣:app.get('/form', function(req, res){res.render('form.ejs', {computers: computers});});總體而言,一切似乎都運行良好,表單按預期填充:<select id = 'computer' name = 'computer'>        <% for (var i = 0; i<computers.length; i++) { %>          <option value = '<%= computers[i].slug %>'><%= computers[i].name %></option>          <% } %>        </select>但是,我從表單收到的數(shù)據(jù)僅提供了數(shù)據(jù)。我的問題是,有沒有一種好方法可以使用 slug 鍵從字典數(shù)組中獲取名稱?我已經嘗試過這樣的方法,但它不起作用,我想知道是否是因為它們在數(shù)組中?app.post('/form', function(req, res){  var c_slug = req.body.computer;  var name = computers[c_slug];  console.log(c_slug);  console.log(name);  res.send('Success!')});我在搜索中找不到任何與此相關的內容。我找到了映射解釋,但它獲取了給定鍵的所有值。我希望我錯過了一些明顯的東西!
查看完整描述

2 回答

?
縹緲止盈

TA貢獻2041條經驗 獲得超4個贊

您可以使用Array.find()方法來查找數(shù)組中符合給定條件的元素。

它返回數(shù)組中滿足所提供的測試函數(shù)的第一個元素值。否則,返回。undefined

app.post('/form', function(req, res){

? const c_slug = req.body.computers;

? const element = computers.find(el => el.slug === c_slug);

? // element is either an element that was found or undefined

? if (element) {

? ? ?const name = element.name;

? ? ?// the above can be written like this in ES6

? ? ?// const { name } = element;


? ? ?// do something

? } else {

? ? ?// return 400 (Bad Request)

? }

...

PS我使用constvar是ES6語法和箭頭函數(shù)?() => ...。兩者都可以在 NodeJS 8+ 的服務器端使用。



查看完整回答
反對 回復 2024-01-18
?
紅糖糍粑

TA貢獻1815條經驗 獲得超6個贊

你可以使用 .find() 方法


app.post('/form', function(req, res){

  var c_slug = req.body.computers;

  var computer = computers.find(el => el.slug === c_slug);

  console.log(c_slug);

  console.log(computer.name);

  res.send('Success!')

});

或者你可以手動查找


app.post('/form', function(req, res){

  var c_slug = req.body.computers;

  var name ;   

  for (let i = 0; i < computers.length; i++) {

    if (computers[i]['slug'] === c_slug) {

      name = computers[i]['slug'];

      break;

    }

  }

  console.log(c_slug);

  console.log(name);

  res.send('Success!')

});


查看完整回答
反對 回復 2024-01-18
  • 2 回答
  • 0 關注
  • 204 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號