用于检测非现有对象中的 JSON 属性的函数
Function For Detecting JSON Properties In Non Existing Objects
有没有办法在不提供特定对象的情况下检查 JSON 中是否存在属性?
例如
data.programs.text.background
background
是text
的财产。但是,如果当前对象中不存在text
对象怎么办?
杰森:
{
"programs": [
{
"width": 500,
"height": 600,
"text": {
"foreground": "black",
"background": "white"
}
},
{
"width": 100,
"height": 200
},
{
"width": 800,
"height": 300,
"text": {
"foreground": "yellow",
"background": "red"
}
}
]
}
控制台将给出错误Uncaught TypeError: Cannot read property 'background' of undefined
测试data.programs.text.background == undefined
不起作用。
是否可以编写一个函数来检测对象是否存在以及属性是否存在,只需提供对对象属性(如 data.programs.text.background
)的引用?
可以使用
.hasOwnProperty()
来确定对象是否具有该对象的属性。
遍
历路径并使用Object.prototype.hasOwnProperty
function exists(object, path) {
if (path.length === 0) {
return true;
}
return Object.prototype.hasOwnProperty.call(object, path[0])
&& exists(object[path[0]], path.slice(1));
}
console.log(exists({}, [ "foo", "bar" ])); // false
console.log(exists({ "foo": { "bar": {} } }, [ "foo", "bar" ])); // true
console.log(exists({ "hasOwnProperty": { "bar": {} } }, [ "hasOwnProperty", "bar" ])); // true
// usage:
exists(data, [ "programs", "text", "background" ]);
我有另一个想法。
你可以做:
function exists(string, context) {
var parts = string.split("."), part;
context = context || window;
while (parts.length > 0) {
part = parts.shift();
if (Object.prototype.hasOwnProperty.call(context, part) === false) {
return false;
}
context = context[part];
}
return true;
}
exists("data.programs.text.background");
使用以下代码查找是否存在的属性。
var data = {
"programs": [
{
"width": 500,
"height": 600,
"text": {
"foreground": "black",
"background": "white"
}
},
{
"width": 100,
"height": 200
},
{
"width": 800,
"height": 300,
"text": {
"foreground": "yellow",
"background": "red"
}
}
]
}
function isPropThere(root, prop){
var keys = prop.split(/[.,'[']]+/);
for(var i=1; i< keys.length; i++){
root = root[keys[i]]
console.dir(root)
if(Array.isArray(root)){
root = root[keys[++i]];
continue;
}
if(!root){
return alert('property not present');
}
}
return alert('property present '+root);
}
isPropThere(data, 'data.programs[0].text.background'); // present - white
isPropThere(data, 'data.programs[1].text.background'); // not present
isPropThere(data, 'data.programs[2].text.background'); // present - red
相关文章:
- 正在打印JSON属性
- 如何将返回一串数字的 JSON 属性转换为日期
- 如何在 JSF 中将 JS 函数作为 JSON 属性传递给前端
- 使用循环更新 JSON 属性值
- 获取json属性duktape
- 正在创建JSON属性
- 当鼠标悬停在一行上时,哪个plot.ly json属性可以显示所有悬停数据
- 访问等于 javascript 中特定值的 JSON 属性
- 具有嵌套 json 属性的行
- 对 JSON 属性进行分组和合并
- 将参数作为引用传递以获取 JSON 属性
- 基于 JSON 属性的角度 img 开关
- 使用变量访问 JSON 属性(字符串)
- 如何获取基于另一个属性的 JSON 属性
- 如何在解析时更改 JSON 属性名称
- 角度 ng-grid:如何访问以递增整数命名的 json 属性
- 返回 JSON 属性
- Nodejs JSON 属性未定义
- Angularjs 如何将 json 属性(Set 或数组)绑定到动态输入表单
- 无法动态获取正确的 json 属性