Use reduce operations to operate on objects
P粉423694341
2023-08-18 14:05:11
<p>This is my input:<code>{field1: {field2:'123', field3:{field4:'123'}}}</code></p>
<p>The target is:<code>{field1: {update: {field2:'123', field3: {update: {field4:'123'}}</code></p>
<p>This is what I tried: </p>
<pre class="brush:php;toolbar:false;">function updateDictHelper(obj) {
Object.entries(obj).reduce((updateClause = {}, [key, value]) => {
if (typeof value !== 'object') {
return {... updateClause, [key]: value}
} else {
return {... updateClause, [key]: {update: updateDictHelper(value)}}
}
})
}</pre>
<p>However, I can't get it to work no matter what. I'm very new to Java/TypeScript and any help would be greatly appreciated. </p>
You have two problems, the first problem is that your
updateDirectHelper
function does not return anything. Although there is areturn
statement in this function, it is actually a callback function nested inreduce
(updateClause, [key, value]) => {
instead ofupdateDictHelper
itself.Another question you have is how to provide a default value for
acc
. Reduce natively supports the optional second parameter , which will be used as the initial value ofacc
.The best approach is to provide an initial value whenever possible. If you don't include it,
.reduce()
will skip the first invocation of the callback and start calling the callback function withacc
set to the first value in the array, and set the second parameter to the second value in the array. If your array has only one value, as in your case, then this single value is the value returned from the.reduce()
call, and your.reduce()
The callback function will never be called: