有没有办法在不提供特定对象的情况下检查JSON中是否存在属性?
例如,
data.programs.text.background
background
是text
的属性。但是如果当前对象中不存在text
对象怎么办?
JSON:
{
"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
等对象属性的引用来编写检测对象是否存在以及属性是否存在的函数?
答案 0 :(得分:2)
您可以使用.hasOwnProperty()
来确定某个对象是否具有该对象的属性。
答案 1 :(得分:2)
遍历路径并使用db2 connect to DB_NAME USER DB_USER using DB_PASSWORD
db2 set SCHEMA=SCHEMA1
db2
db2 => SELECT C.id FROM table C WHERE C.col1 IN ('xyz-asd-asd') with ur
ID
----------------------------------------------------------------
123
1 record(s) selected.
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" ]);
答案 2 :(得分:1)
使用以下代码查找属性。
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
&#13;