Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Transform nested object to keys-values
let tmpResult:{ [key: string]: any} = {};
/**
* Transform an nested object to keys-values object
* @export
* @param {object} obj
* @param {string[]} [key=[]]
* @returns {object}
*/
export default function objectTokeyValue(obj: any, key:string[] = [], first: boolean = true):any {
if (first) {
tmpResult = {};
}
if (typeof obj === 'object' && obj !== null && !Array.isArray(obj)) {
const k = Object.keys(obj);
for (let i = 0; i < k.length; i += 1) {
if (typeof obj[k[i]] !== 'object') {
tmpResult[key.concat([k[i]]).join('_')] = obj[k[i]];// @ts-ignore
} else if (obj[k[i]] !== null) {
key.push(k[i]);
objectTokeyValue(obj[k[i]], Object.assign([], key), false);
key.pop();
}
}
}
return { ...tmpResult };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.