I have an object that is structured like this (simplified version):
{
"customConfig": {
"homepage": {
"url": "path/to/homepage",
"base_path": "www.stackoverflow.com"
},
"portfolio": {
"url": "path/to/portfolio",
"base_path": "www.github.com"
},
"moreStuff": {
//...
}
}
Now I want to check whether a specific string value (in my case for the key base_path) exists.
So how can I check whether, for example, the string
www.github.comexists in mycustomConfigobject for the keybase_path?
A boolean return value would be enough here.
The OP needs to utilize Object.values in order to retrieve an array of all the config object's property values. Then the OP wants to know if some condition like such a value's/item's base_path value equals a certain address.
console.log(
"does object contain an item where `base_path` equals 'www.github.com' ?",
Object.values({
"homepage": {
"url": "path/to/homepage",
"base_path": "www.stackoverflow.com"
},
"portfolio": {
"url": "path/to/portfolio",
"base_path": "www.github.com"
},
"moreStuff": {
//...
}
}).some(item => item.base_path === 'www.github.com')
);
You could use a recursive function.
To find a certain key, call hasOwnProperty (or use includes on Object.keys) at each nesting level to see if the key is found there.
To find a certain value, use includes on Object.values().
To find a key/value pair, find the key (as above) and verify that the value for that key is the searched value:
const containsKey = (obj, key) => Object(obj) === obj && (
obj.hasOwnProperty(key) ||
Object.values(obj).some(child => containsKey(child, key))
);
const containsValue = (obj, value) => Object(obj) === obj && (
Object.values(obj).includes(value) ||
Object.values(obj).some(child => containsValue(child, value))
);
const containsKeyValue = (obj, key, value) => Object(obj) === obj && (
obj.hasOwnProperty(key) && obj[key] === value ||
Object.values(obj).some(child => containsKeyValue(child, key, value))
);
// Example run:
let data = {
"customConfig": {
"homepage": {
"url": "path/to/homepage",
"base_path": "www.stackoverflow.com"
},
"portfolio": {
"url": "path/to/portfolio",
"base_path": "www.github.com"
},
"moreStuff": {
//...
}
}
};
console.log(containsKey(data, "base_path")); // true
console.log(containsValue(data, "www.github.com")); // true
console.log(containsKeyValue(data, "base_path", "www.github.com")); // true
You can try something like
let obj = {
"customConfig": {
"homepage": {
"url": "path/to/homepage",
"base_path": "www.stackoverflow.com"
},
"portfolio": {
"url": "path/to/portfolio",
"base_path": "www.github.com"
}
}
}
let exist = Object.keys(obj.customConfig).filter(page => obj.customConfig[page]['base_path'] == 'www.github.com').length>0;
console.log(exist);