簡體   English   中英

更好的方法來解構 JavaScript 中的有效載荷嵌套的 object?

[英]Better way to destructure object nested from payload in JavaScript?

我有這個 function:

const id = await this.$axios(config)
               .then(({ data : { user : { profile : { profileId } }}}) => profileId || 0 )

為了簡單

const id = ({ a : { b : { c : { id } } } } ) => id || 0

null 檢查這個而不在運行時崩潰的最佳方法是

const id = ({ a : { b : { c : { id } = {} } = {} } = {} } = {} ) => id || 0

正如你所看到的,不像這個那樣可讀

const id = (data) => a?.b?.c?.c?.id || 0

即使該屬性可能不存在或者 object 是另一種類型,是否還有其他方法可以解構?

出色地。 不管你的問題,我最好還是這樣做:

  1. this.$axios.get().then().catch()... 或
  2. aysnc function (){ 常量 {數據,狀態} = 等待 $axios.get()

}

暫無
暫無

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

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