skip to Main Content

I am looking for a solution to add additional keys to an object.

array = [{A: 5, B:10, C: 20},{A: 3, B: 2, C: 5}];

In the next step i will calculate a new_value:

array.forEach((element) => {
 let new_value = ((element.A + element.B) / element.C;

Now, i have to add the result to each object in the above mentioned array:

array = array.map(element => new_value);

The outcome should be:

array = [{A: 5, B:10, C: 20, new_value: 0.75},{A: 3, B: 2, C: 5, new_value: 1.2}];

Unfortunately that´s not the case! How can I add the calculated value to the object?

2

Answers


  1. From my above comments …

    "Already the second code example comes with a(n at least two times) broken syntax. How should the audience know whether it sees just a fraction of the OP’s code or indeed a broken script? If at all utilizing forEach the code should look close to … array.forEach(element => element.new_value = ((element.A + element.B) / element.C)); … which of cause mutates each item of array thus the latter as well."

    const array = [
      { A: 5, B: 10, C: 20 },
      { A: 3, B: 2, C: 5 },
    ];
    
    const newArray = array
      // - `map`ping should never mutate the original `array`.
      .map(({ A, B, C }) => ({
        A, B, C, new_value: (A + B) / C
      }));
    
    console.log({ array, newArray });
    
    array
      // - with `forEach` one usually would mutate
      //   each of an operated array's item.
      .forEach(item =>
        item.new_value = (item.A + item.B) / item.C
      );
    
    console.log({ array });
    .as-console-wrapper { min-height: 100%!important; top: 0; }
    Login or Signup to reply.
  2. Simple enough

    Code.gs

    function test() {
      try {
        let array = [{A: 5, B:10, C: 20},{A: 3, B: 2, C: 5}];
        array.forEach( element => {
            element.D = (element.A+element.B)/element.C;
          }
        );
        console.log(array);
      }
      catch(err) {
        console.log(err);
      }
    }
    

    Execution log

    7:04:19 AM  Notice  Execution started
    7:04:19 AM  Info    [ { A: 5, B: 10, C: 20, D: 0.75 }, { A: 3, B: 2, C: 5, D: 1 } ]
    7:04:20 AM  Notice  Execution completed
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search