Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function flatten(source, key) {
- let it, index = 0;
- const flattened = {};
- const delim = key !== undefined ? '.' : '';
- key = key || '';
- if (typeof source === 'string') {
- flattened[key] = source;
- return flattened;
- }
- for (const prop in source) {
- it = source[prop];
- // STEP 2 - determine if the value property is an object, array, or value
- if (Array.isArray(it)) {
- // STEP 2.1 - it's an array, iterate over the array and get key for each obj
- index = 0;
- for (const obj of it) {
- key = delim + prop + '.' + index;
- Object.assign(flattened, flatten(obj, key));
- index++;
- }
- } else if (typeof it === 'object' && it !== null) {
- // STEP 2.2 - it's an object, traverse
- Object.assign(flattened, flatten(it, key + delim + prop));
- } else {
- // STEP 2.3 - The leaf - set the value
- flattened[key + delim + prop] = it;
- }
- }
- return flattened;
- }
Add Comment
Please, Sign In to add comment