亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

從對象數組中獲取價值的更好方法是什么?數組過濾器() 替代?

從對象數組中獲取價值的更好方法是什么?數組過濾器() 替代?

蕭十郎 2022-09-29 16:31:42
const incoming = "disi";const sexEnumeration = [  { key: "bebek", label: "ребенок" },  { key: "erkek", label: "Мужчина" },  { key: "disi", label: "женская кошка" }];let message = sexEnumeration.filter((item) =>        item.key == incoming ? item.label : false      )[0].labelconsole.log(sexEnumeration.filter((item) => item.key == incoming ? item.label : false)[0].label);有沒有更好的方法來獲取消息,而不是這個丑陋的數組過濾器。編輯兩種解決方案都很好。我會去地圖解決方案。但我認為最好對小數組使用 .find。我已經在一個 vue 示例中應用了解決方案。https://codepen.io/kaanna/pen/BajKPOr
查看完整描述

2 回答

?
BIG陽

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

可以使用 Array.find()而不是使用 ,它返回數組中通過回調函數中實現的測試的所有元素,它Array.filter()sexEnumeration

返回提供的數組中滿足所提供測試函數的第一個元素的值

這是如何完成的:

const message = (sexEnumeration.find((item) =>
    item.key === incoming ? item.label : false
    )).label

以下是工作,簡潔的示例(包括@3limin4t0r的建議):

const incoming = "disi";

const sexEnumeration = [

  { key: "bebek", label: "ребенок" },

  { key: "erkek", label: "Мужчина" },

  { key: "disi", label: "женская кошка" }

];


const { label: message } = sexEnumeration.find(({ key }) => (

  key == incoming

));


console.log(message);


查看完整回答
反對 回復 2022-09-29
?
幕布斯7119047

TA貢獻1794條經驗 獲得超8個贊

一種選擇是將數組轉換為 Map 以進行快速查找。在這里,數組的使用似乎并不合適。這確實假定項屬性在項之間是唯一的。key


const sexEnumeration = [

  { key: "bebek", label: "ребенок" },

  { key: "erkek", label: "Мужчина" },

  { key: "disi", label: "женская кошка" }

];

const sexEnumerationMap = new Map(sexEnumeration.map(item => [item.key, item]));


console.log(sexEnumerationMap.get("disi").label);

console.log(sexEnumerationMap.get("bebek").label);

console.log(sexEnumerationMap.get("erkek").label);


查看完整回答
反對 回復 2022-09-29
  • 2 回答
  • 0 關注
  • 96 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

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

公眾號

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