[英]Javascript - avoiding asynchronous race condition when checking object property existence
[英]Checking existence of nested property in an object javascript
我已經回顧了這個問題的一些答案,但是,我想以不同的方式提出我的問題。
假設我們有一個字符串: “level1.level2.level3 ....” ,表示名為Obj的對象中的嵌套屬性。
關鍵是我們可能不知道該字符串中存在多少嵌套屬性。 例如,它可以是“level1.level2”或“level1.level2.level3.level4”。
現在,我想要一個給出Obj和屬性字符串作為輸入的函數,只需告訴我們,如果對象中存在這樣的嵌套屬性(假設為true或false作為輸出)。
更新:感謝@Silvinus,我發現了一個小修改的解決方案:
private checkNestedProperty(obj, props) {
var splitted = props.split('.');
var temp = obj;
for (var index in splitted) {
if (temp[splitted[index]] === 'undefined' || !temp[splitted[index]]) return false;
temp = temp[splitted[index]];
}
return true;
}
您可以使用此功能探索您的Obj:
var fn = function(obj, props) {
var splited = props.split('.');
var temp = obj;
for(var index in splited) {
if(typeof temp[splited[index]] === 'undefined') return false;
temp = temp[splited[index]]
}
return true
}
var result = fn({ }, "toto.tata");
console.log(result); // false
var result = fn({ toto: { tata: 17 } }, "toto.tata");
console.log(result); // true
var result = fn({ toto: { tata: { tutu: 17 } } }, "toto.foo.tata");
console.log(result); // false
此函數允許探索Obj的嵌套屬性,該屬性取決於參數中傳遞的props
您可以通過迭代鍵並檢查它是否在給定對象中來使用Array#every()
和thisArg
。
var fn = function (o, props) { return props.split('.').every(k => k in o && (o = o[k])); } console.log(fn({}, "toto.tata")); // false console.log(fn({ toto: { tata: 17 } }, "toto.tata")); // true console.log(fn({ toto: { tata: { tutu: 17 } } }, "toto.foo.tata")); // false
這個答案提供了你的問題的基本答案。 但需要調整它來處理未定義的情況:
function isDefined(obj, path) {
function index(obj, i) {
return obj && typeof obj === 'object' ? obj[i] : undefined;
}
return path.split(".").reduce(index, obj) !== undefined;
}
根據@Silvinus給出的解決方案,如果你在嵌套對象中處理數組,這是一個解決方案(因為在數據庫查詢的結果中通常就是這種情況):
checkNested = function(obj, props) {
var splited = props.split('.');
var temp = obj;
for(var index in splited) {
var regExp = /\[([^)]+)\]/;
var matches = regExp.exec(splited[index])
if(matches) {
splited[index] = splited[index].replace(matches[0], '');
}
if(matches) {
if(matches && typeof temp[splited[index]][matches[1]] === 'undefined') return false;
temp = temp[splited[index]][matches[1]];
}
else {
if(!matches && typeof temp[splited[index]] === 'undefined') return false;
temp = temp[splited[index]]
}
}
return true
}
obj = {ok: {ao: [{},{ok: { aa: ''}}]}}
console.log(checkNested(obj, 'ok.ao[1].ok.aa')) // ==> true
console.log(checkNested(obj, 'ok.ao[0].ok.aa')) // ==> false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.