用于检测非现有对象中的 JSON 属性的函数

Function For Detecting JSON Properties In Non Existing Objects

本文关键字:JSON 属性 函数 对象 检测 用于      更新时间:2023-09-26

有没有办法在不提供特定对象的情况下检查 JSON 中是否存在属性?

例如

data.programs.text.background

backgroundtext的财产。但是,如果当前对象中不存在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