cval
v1.0.1
Published
Function to safe get chain value with default value, and avoid 'Cannot read property of undefined' errors
Downloads
15
Maintainers
Readme
cval
Description
It's a function to safe get chain value with default value, and avoid 'Cannot read property of undefined' errors.
提供链式调用函数
Useage
//you can view detail in test/index.js
var testModel = {
"a": {
"b": {
"c": {
"d": "valueD"
}
}
},
"a1": ["b1", "b2", "b3", "b4"],
"a2": [{
"b2": {
"c2": [{
"d2": {
"e2": "valueE"
}
}]
}
}]
};
cval(testModel, 'a.b.c.d')
//'valueD'
cval(testModel, 'a.b.c.d.e.f')
//''
cval(testModel, 'a.b.c.d.e.f', 'Error')
//'Error'
cval(testModel, 'a2[0].b2.c2[0].d2.e2')
//valueE
testModel.cval('a2[0].b2.c2[0].d2.e2');
//valueE
Advance
//before
//if data has error, will throw 'Cannot read property of undefined' error
if(testModel.a2[0].b2.c2[0].d2.e2){
//do something
}
//ensure version
if(testModel&&testModel.a2&&testModel.a2[0]&&testModel.a2[0].b2&&testModel.a2[0].b2.c2&&testModel.a2[0].b2.c2){
//do something
}
//now
var result = cval(testModel, 'a2[0].b2.c2[0].d2.e2', false);
if(result){
//do something
}