Use reduce operations to operate on objects
P粉423694341
P粉423694341 2023-08-18 14:05:11
0
1
522
<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>
P粉423694341
P粉423694341

reply all(1)
P粉909476457

You have two problems, the first problem is that your updateDirectHelper function does not return anything. Although there is a return statement in this function, it is actually a callback function nested in reduce(updateClause, [key, value]) => { instead of updateDictHelper 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 of acc.

reduce(callbackFn, initialValue)

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 with acc 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:

const arrayWithOneElement = [1];
const res = arrayWithOneElement.reduce(() => {
  console.log("I never run");
}); // 注意没有第二个参数
console.log(res);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template