Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
-3
rated 0 times [  4] [ 7]  / answers: 1 / hits: 30043  / 7 Years ago, wed, november 1, 2017, 12:00:00

I'm looking for something kind of like Object.keys but that works for potentially nested objects. It also shouldn't include keys that have object/array values (it should only include keys with immediate string/number/boolean values).



Example A



Input



{
check_id:12345,
check_name:Name of HTTP check,
check_type:HTTP
}


Expected output



[
check_id,
check_name,
check_type
]


Object.keys would work for flat cases like this, but not for nested cases:



Example B



Input



{
check_id:12345,
check_name:Name of HTTP check,
check_type:HTTP,
tags:[
example_tag
],
check_params:{
basic_auth:false,
params:[
size
],
encryption: {
enabled: true,
}
}
}


Expected output



[
check_id,
check_name,
check_type,
check_params.basic_auth,
check_params.encryption.enabled
]


Note that this does not include tags, check_params, check_params.params, or check_params.encryption since these values are arrays/objects.



The question



Is there a library that does this? How would you implement it so that it can work with any object, large and nested, or small?


More From » arrays

 Answers
2

You could use reduce like this:




const keyify = (obj, prefix = '') => 
Object.keys(obj).reduce((res, el) => {
if( Array.isArray(obj[el]) ) {
return res;
} else if( typeof obj[el] === 'object' && obj[el] !== null ) {
return [...res, ...keyify(obj[el], prefix + el + '.')];
}
return [...res, prefix + el];
}, []);

const input = {
check_id:12345,
check_name:Name of HTTP check,
check_type:HTTP,
tags:[
example_tag
],
check_params:{
basic_auth:false,
params:[
size
],
encryption: {
enabled: true,
testNull: null,
}
}
};

const output = keyify(input);

console.log(output);




Edit1: For the general case where you want to include arrays.




const keyify = (obj, prefix = '') => 
Object.keys(obj).reduce((res, el) => {
if( typeof obj[el] === 'object' && obj[el] !== null ) {
return [...res, ...keyify(obj[el], prefix + el + '.')];
}
return [...res, prefix + el];
}, []);

const input = {
check_id:12345,
check_name:Name of HTTP check,
check_type:HTTP,
tags:[
example_tag
],
nested: [
{ foo: 0 },
{ bar: 1 }
],
check_params:{
basic_auth:false,
params:[
size
],
encryption: {
enabled: true,
testNull: null,
}
}
};

const output = keyify(input);

console.log(output);




[#56042] Monday, October 30, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gianni

Total Points: 307
Total Questions: 104
Total Answers: 96

Location: South Georgia
Member since Sun, Aug 8, 2021
3 Years ago
;