[英]Better / Faster way to extract value with a matched property on different depth on a nested object with condition
[英]Better way for checking nested object in `if` condition?
考慮我有這樣一個對象:
Obj.Boo.Foo.Zoo
好了,如果我想確定zoo
有一個值而不是空的,我應該這樣做:
if(Obj != null && Obj.Boo != null && Obj.Boo.Foo != null && Obj.Boo.Foo.Zoo != null) {
//blah blah
}
如果我在Zoo
之后有更多的嵌套對象,我應該擴展if
並且代碼變得有點格式錯誤。
有沒有更好的方法來做這種類型的條件?
我保留了一個小函數我調用chainGet(obj, chain, default)
解決這種情況:
function chainGet(obj, chain, dflt) {
if (typeof chain === "string")
chain = chain.split(".");
var result = obj;
for (var i = 0; i < chain.length; i += 1) {
if (result === undefined)
break;
result = result[chain[i]];
}
return result === undefined? dflt : result;
}
例如:
> chainGet({ foo: 42 }, "foo")
42
> chainGet({ foo: 42 }, "bar", "x")
'x'
> chainGet({ foo: { bar: 42 }}), "foo.bar")
42
這甚至適用於數組:
> chainGet([{ foo: [42] }], [0, "foo", 0])
42
當然,虛線訪問的長鏈是代碼氣味 ,因此在使用它們時應該謹慎行事......但有時你只需要這樣做;)
如果你真的不需要處理這種情況,那么一個不好的做法是嘗試在try catch語句中訪問Object
try{
// access Obj.Boo.Foo.Zoo
}
catch{
// catch a NullReferenceException
}
更好的方法是修改getter和setter,以便在嘗試訪問子對象及其null時,父對象拋出一個合適的異常或處理它。 在這種情況下,檢查第一個對象就足夠了。
它可以在不使用功能的情況下實現。 快捷方法可以是 -
if(((((Obj || {}).Boo || {}).Foo || {}).Zoo || {}) != {}) {
// Zoo has a value and not empty
}
或ES6方式 -
const checkNull = (keys, Object) =>
keys.reduce((Obj, o) =>
(Obj && Obj[o]) ? Obj[o] : null, Object)
console.log(checkNull(['Boo', 'Foo', Zoo], Obj))
// [Value of Zoo]
console.log(checkNull(['Boo', 'Foo1', Zoo], Obj))
// null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.