3 回答

TA貢獻1797條經(jīng)驗 獲得超6個贊
您可以創(chuàng)建一個通用方法,該方法基于屬性名稱數(shù)組訪問元素,該屬性名稱數(shù)組被解釋為通過屬性的路徑:
function getValue(data, path) {
var i, len = path.length;
for (i = 0; typeof data === 'object' && i < len; ++i) {
data = data[path[i]];
}
return data;
}
然后,您可以使用以下命令調(diào)用它:
var a = getValue(b, ["c", "d"]);

TA貢獻1804條經(jīng)驗 獲得超7個贊
標準方法:
var a = b && b.c && b.c.d && b.c.d.e;
速度非??欤惶珒?yōu)雅(尤其是具有較長的屬性名稱)。
使用函數(shù)遍歷JavaScipt對象屬性既不高效也不優(yōu)雅。
嘗試以下方法:
try { var a = b.c.d.e; } catch(e){}
如果您確定a以前沒有使用過,或者
try { var a = b.c.d.e; } catch(e){ a = undefined; }
如果您之前已經(jīng)分配過。
這可能比第一種選擇更快。

TA貢獻1820條經(jīng)驗 獲得超2個贊
獲取的價值path的object。如果解析的值為undefined,defaultValue則返回。
在ES6中,我們可以從Object下面的類似代碼片段中獲取嵌套屬性。
const myObject = {
a: {
b: {
c: {
d: 'test'
}
}
},
c: {
d: 'Test 2'
}
},
isObject = obj => obj && typeof obj === 'object',
hasKey = (obj, key) => key in obj;
function nestedObj(obj, property, callback) {
return property.split('.').reduce((item, key) => {
if (isObject(item) && hasKey(item, key)) {
return item[key];
}
return typeof callback != undefined ? callback : undefined;
}, obj);
}
console.log(nestedObj(myObject, 'a.b.c.d')); //return test
console.log(nestedObj(myObject, 'a.b.c.d.e')); //return undefined
console.log(nestedObj(myObject, 'c.d')); //return Test 2
console.log(nestedObj(myObject, 'd.d', false)); //return false
console.log(nestedObj(myObject, 'a.b')); //return {"c": {"d": "test"}}
添加回答
舉報