Рекурсия есть:
const nestedToPlain = (obj, path = '') =>
Object.entries(obj).reduce((acc, [ k, v ]) => {
const newPath = `${path}${path ? '.' : ''}${k}`;
return Object.assign(acc, v instanceof Object
? nestedToPlain(v, newPath)
: { [newPath]: v }
);
}, {});
const plain = nestedToPlain(example, 'example');
или
const nestedToPlain = (obj, keys = []) =>
Object.entries(obj).reduce((acc, [ k, v ]) => (
keys.push(k),
Object.assign(acc, v instanceof Object
? nestedToPlain(v, keys)
: { [keys.join('.')]: v }
),
keys.pop(),
acc
), {});
const plain = nestedToPlain(example, [ 'example' ]);
Рекурсии нет:
const nestedToPlain = function(obj, keys = []) {
const result = {};
const [ push, pop ] = this;
for (const stack = [ obj ]; stack.length;) {
const n = stack.pop();
if (n instanceof Object) {
Object.entries(n).reverse().forEach(([ k, v ]) => stack.push(pop, v, k, push));
} else if (n === push) {
keys.push(stack.pop());
} else if (n === pop) {
keys.pop();
} else {
result[keys.join('.')] = n;
}
}
return result;
}.bind([ Symbol(), Symbol() ]);
const plain = nestedToPlain(example, [ 'example' ]);