Skip to content

Instantly share code, notes, and snippets.

@ovarunendra
Created September 4, 2021 03:46
Show Gist options
  • Save ovarunendra/55b623c0b1c50765714cec010c0eb902 to your computer and use it in GitHub Desktop.
Save ovarunendra/55b623c0b1c50765714cec010c0eb902 to your computer and use it in GitHub Desktop.
Object to Nested Keys (VV)
var jsData = {
tabs: {
home: 'HOME',
explore: 'EXPLORE',
sell: 'SELL',
blogs: 'BLOGS',
profile: 'PROFILE',
},
homeScreen: {
title: 'Pashushala',
},
};
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);
byString = function(o, s) {
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
s = s.replace(/^\./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
o = o[k];
} else {
return;
}
}
return o;
}
var finalObj = {}
output.forEach(k => {
console.log(byString(input, k))
finalObj[k] = byString(input, k)
})
console.log(finalObj)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment