Reputation: 1068
Is there a way to check whether or not a property exists in JSON without providing a specific object?
For example,
data.programs.text.background
background
is the property of text
. But what if a text
object does not exist in the current object?
JSON:
{
"programs": [
{
"width": 500,
"height": 600,
"text": {
"foreground": "black",
"background": "white"
}
},
{
"width": 100,
"height": 200
},
{
"width": 800,
"height": 300,
"text": {
"foreground": "yellow",
"background": "red"
}
}
]
}
The console would give an error of Uncaught TypeError: Cannot read property 'background' of undefined
Testing for data.programs.text.background == undefined
does not work.
Can a function be written that detects whether not the object exists and whether or not the property exists by simply providing reference to an object property such as data.programs.text.background
?
Upvotes: 2
Views: 346
Reputation: 5681
Use below code to find is the property present.
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
Upvotes: 1
Reputation: 57721
Traverse the path and use 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" ]);
I had another idea.
You could do:
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");
Upvotes: 2
Reputation: 7008
You can use .hasOwnProperty()
to determine if an object has the property on the object.
Upvotes: 2