我有一个有很多深层嵌套属性的对象。我希望能够访问" MY_KEY" (如下),但如果不存在,则获取" MY_OTHER_KEY"。我怎么能做到这一点?
const {
X: {
Y: {
MY_KEY: {
Values: segments = []
} = {}
} = {}
} = {}
} = segment;
答案 0 :(得分:2)
你可以使用解构赋值中的时间变量来实现这一点,如下所示:
function destructure(segments) {
const {
X: {
Y: {
MY_OTHER_KEY: _fallback_value = {},
MY_KEY: {
Values: segment = []
} = _fallback_value,
} = {},
} = {},
} = segments;
return segment;
}
console.log(destructure({})); // []
console.log(destructure({X:{}})); // []
console.log(destructure({X:{Y:{MY_KEY:{Values:"A"}}}})); // A
console.log(destructure({X:{Y:{MY_OTHER_KEY:{Values:"B"}}}})); // B
console.log(destructure({X:{Y:{MY_OTHER_KEY:{Values:"C"}, MY_KEY:{Values:"D"}}}})); // D

首先,这种解构将尝试一直提取第二个密钥,这可能会产生一些意想不到的影响,例如MY_OTHER_KEY
的属性获取器将始终运行。
然而,我没有看到它的美丽。在解构中隐藏一些控制流程只是令人困惑。我宁愿建议提取父对象并对其使用常规属性访问:
function destructure(segments) {
const {
X: {
Y: nested = {},
} = {},
} = segments;
const selected = nested.MY_KEY || nested.MY_OTHER_KEY || {};
const {
Values: segment = []
} = selected;
return segment;
}
console.log(destructure({})); // []
console.log(destructure({X:{}})); // []
console.log(destructure({X:{Y:{MY_KEY:{Values:"A"}}}})); // A
console.log(destructure({X:{Y:{MY_OTHER_KEY:{Values:"B"}}}})); // B
console.log(destructure({X:{Y:{MY_OTHER_KEY:{Values:"C"}, MY_KEY:{Values:"D"}}}})); // D

答案 1 :(得分:1)
检查目标是否已定义
>>> x = "%s/%s/%s" % (input("month: "), input("day: "), input("year: "))
month: 11
day: 01
year: 2016
>>> x
'11/01/2016'
如果您尝试将目标分配给其他属性,如果之前的目标定义为.grid {
padding-bottom: 80px;
}
.grid:after {
content: "";
display: table;
clear: both;
}
,您可以在后续目标定义中分配变量
let {/* do destructuring stuff */}
if (MY_KEY === undefined) {
// define `MY_OTHER_KEY` variable here
}
答案 2 :(得分:1)
虽然对象解构很酷且很新,但在所有情况下并不是最好的。可以这样做:
<!DOCTYPE html>
<style>
#border {
border: 2px solid;
border-image: url(hr.gif) 10 round;
}
</style>
<div id="border"><p>The quick brown fox jumps over the lazy dog</p></div>