I want to check if a deeply nested object consists of single key-value pair, if it does, it should return true else false.
For e.g., I want the below code to return true
,
var test = {
level1:
{
level2:
{
level3:'level3'
}
}
};
And the below code to return false
,
var test2 = {
level1: {
level2: {'a': '1', 'b': 2},
level3: {'a': '2', 'c': 4}
}
};
Also, the below code should return true
,
var test3 =
{
level1: {
level2: {
level3: {
level4: {
1: "1",
2: "2",
3: "3",
4: "4"
}
}
}
}
}
I made the following program for it, but it doesn't work,
function checkNested(obj) {
if(typeof(obj) === 'object') {
if(Object.keys(obj).length === 1) {
var key = Object.keys(obj);
checkNested(obj[key])
} else {
return(false);
}
}
return(true);
}
Could someone please suggest me how can I achieve it?
1 Answer 1
With var key = Object.keys(obj);
, key
becomes an array (containing the one key), so obj[key]
doesn't make sense. You might destructure the [key]
instead:
const [key] = Object.keys(obj);
return checkNested(obj[key])
(make sure to return
the recursive call)
Or, even better, use Object.values
, since you don't actually care about the keys:
var test = {
level1: {
level2: {
level3: 'level3'
}
}
};
var test2 = {
level1: {
level2: 'level2',
level3: 'level3'
}
};
function checkNested(obj) {
if (typeof(obj) === 'object') {
const values = Object.values(obj);
if (values.length !== 1) {
return false;
}
return checkNested(values[0]);
}
return true;
}
console.log(checkNested(test));
console.log(checkNested(test2));
-
Your code is returning false for the below code, var test3 = { level1: { level2: { level3: { level4: { 1: "1", 2: "2", 3: "3", 4: "4" } } } } }Frosted Cupcake– Frosted Cupcake2019年01月21日 10:01:24 +00:00Commented Jan 21, 2019 at 10:01
-
2Yep, because it has more than one nested key-value pair.CertainPerformance– CertainPerformance2019年01月21日 10:02:46 +00:00Commented Jan 21, 2019 at 10:02
-
Hi, I updated my question, I want the code to return true even for test3Frosted Cupcake– Frosted Cupcake2019年01月21日 10:05:58 +00:00Commented Jan 21, 2019 at 10:05
-
It does return false for
test3
. (as your first comment noted)CertainPerformance– CertainPerformance2019年01月21日 10:06:11 +00:00Commented Jan 21, 2019 at 10:06 -
My bad, I want it to return true even in such cases as test3Frosted Cupcake– Frosted Cupcake2019年01月21日 10:07:44 +00:00Commented Jan 21, 2019 at 10:07