I got a deep object:
{
"something": "Homepage",
"else": [
"[replaceme]",
"[replaceme]"
],
"aside": "[replaceme]",
"test": {
"test": {
"testing": [
"[replaceme]",
"[replaceme]",
"variable",
{
"testing": {
"testing": {
"something": "[replaceme]",
"testing": {
"testing": [
"[replaceme]",
"[replaceme]"
]
}
}
}
}
]
}
}
}
Now I need to replace every occurrence of [replaceme]
with something that comes out of a async function. It is different each time.
I thought I reduce each level of the object and return a promise chain.
This is what I got so far:
const IterateObject = ( object ) => {
return new Promise( ( resolve, reject ) => {
Object.keys( object ).reduce( ( sequence, current ) => {
const key = current;
return sequence.then( () => {
return new Promise( ( resolve, reject ) => {
if( typeof object[ key ] === 'object' ) {
IterateObject( object[ key ] )
.then( result => {
newObject[ key ] = result;
});
// ^----- How do I add the next level when it returns a promise?
}
else {
resolve( newObject[ key ] )
}
});
});
}, Promise.resolve())
.catch( error => reject( error ) )
.then( () => {
console.log('done');
resolve();
});
});
}
Question
What is the best way to go about this issue? Maybe a promise chain is not the right tool?