![](/img/trans.png)
[英]Nicest way to check if key in object exists and either set the value or null?
[英]Is there an elegant way to check if a key and value exists in an object and then use it?
一般来说,使用 redux 和 javascript 时,我发现自己输入了冗长的代码行以在 object 中使用单个值。
const mapStateToProps = (state) => ({
valueIwant: state.data && state.data.user && state.data.user.valueIWant || ''
})
I know I could set a default state, but in many cases the data
object could come from an API call or maybe I have tons of data1
, data2
, data3
etc. that all comes from API's and It's not feasible to write default state for all其中。
没有任何速记方法可以做到这一点吗?
将会有,如果你使用 Babel 或类似工具(如果你使用 React,你可能会使用它),你今天就可以使用它:可选链接。
const mapStateToProps = (state) => ({
valueIwant: state.data?.user?.valueIWant || ''
// ^-----^------------------- ***
})
?.
表示如果前面的值为null
或undefined
,则表达式到此结束,结果为undefined
。
您还可以将nullish 合并运算符扔给它:
const mapStateToProps = (state) => ({
valueIwant: state.data?.user?.valueIWant ?? ''
})
仅在前面的末尾使用''
是null
或undefined
(不是其他虚假值,如0
, ''
等)。
这两个提案都是第 3 阶段,JavaScript 引擎正在积极增加对它们的支持。 (Chrome 的 V8 引擎目前有可选的链接,但在标志后面。)
目前,最好的方法是使用像dot-object这样的外部模块。 这是一个例子:
const dotObj = require('dot-object');
const mapStateToProps = (state) => ({
valueIwant: dotObj.pick('data.user.valueIWant', state) || ''
});
将来,将有一种本地方式来引用可选的 object 属性。
我有时会这样做
val = (((this.state || {}).data || {}).user || {}).valueYouWant || defaultValue
如果你有一个数组,你可以做
val = ((this.state || {}).array || [])[index] || defaultValue
只要您确定预期数据的结构,您基本上可以根据需要将其串起来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.