-1

Here is an object of 3 forms formA, formB, formC in which form A and B are objects and formC is an array of objects which can have multiple objects

const object: {
    "formA": {
        "details": {},
        "isRouteUser": false,
        "province": "ON",
        "prelabel": 10,
        "users": [
            {
                "age": 0
            }
        ]
    },
    "formB": {
        "line11": 0,
        "line12": 0,
        "line150_1": 0
    },
    "formC": [
        {
            "price": 0,
            "details": [
                {
                    "subItemPrice": 0
                }
            ]
        }
    ]
}

I am using the function to find the value of the fields inside the forms

    const getValue = (object, keys) => keys.split('.').reduce((o, k) => (o || {})[k], object);

const key1 = formB.line11
const key2 = formC[0].price
const key3 = formC[0].details[0].subItemPrice

I am using this function to get the value

const formValue = getValue(object,key1)

case 1: key 1 worked well

case 2: key2 - works on the selected index it should work for every index of the array

case 3: key3 - failed

bguiz
  • 27,371
  • 47
  • 154
  • 243

1 Answers1

2

The reduce() iterates through the list of array elements and executes the callback function after each iteration ie) it returns the result of the previous iteration as an argument for the next iteration. Reduce function gives a single value as the final result.

const numbers = [5, 10, 15];

document.getElementById("demo").innerHTML = numbers.reduce(sumOfNumbers);

function sumOfNumbers(total, num) {
  return total + num;
}
<!DOCTYPE html>
<html>
<body>

<p>Sum of numbers in an array</p>

<p id="demo"></p>
</body>
</html>

Here, initially, the numbers[0] get passed to the function and checked for the prior result, if no result is found it returns numbers[0] as a result.

In the next iteration, sumOfNumbers(5, 10) is called. Here, 5 is the result of the preceding iteration and 10 is the 2nd element in the array.

Finally, reduce() iterates each element in an array and returns a single value as the final result. In this case, the final result is the sum of elements in the array.