Home  >  Q&A  >  body text

Use reduce operations to operate on objects

<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粉423694341P粉423694341429 days ago491

reply all(1)I'll reply

  • P粉909476457

    P粉9094764572023-08-19 12:39:09

    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);

    reply
    0
  • Cancelreply