Home > database >  How can I add to a multiplier inside an inner for loop?
How can I add to a multiplier inside an inner for loop?

Time:02-05

I have an array of objects, and each object has a nested object with a key that I would like to increment each iteration with a higher multiplier.

I have an object:

object = {
    id: 1,
    innerArr: [
        {
            key: 50
        },
        {
            key: 20
        }
    ]
}

then I want to:

Push it to a new array, X times.

multiply the 'key' with growing increments in each iteration

const arr = [];
let increment = 0.85;

for (let i = 0; i < 7; i  ) {
    const { id } = object;

    object.innerArr.forEach(obj => {
        obj.key *= increment;
    })

    arr.push({
        id,
        innerArr
    })
    increment  = 0.05;    // (1:) 0.9, (2:) 0.95...
}

The resulting array should look something like this:

arr = [
    {
        id: 1,
        innerArr: [
            {
                key: 42.5
            },
            {
                key: 17
            }
        ]
    },
    {
        id: 1,
        innerArr: [
            {
                key: 45
            },
            {
                key: 18
            }
        ]
    },
    {
        id: 1,
        innerArr: [
            {
                key: 47.5
            },
            {
                key: 19
            }
        ]
    } // and the rest...
]

But, for some (probably obvious) reason, when I do something similar, all the keys get the last increment only (the 7th iteration of increment = 0.05).

How can I get the desired output? and, what mechanism am I missing that cause this behavior.

Thanks for the help!

CodePudding user response:

Found the answer! when I copied the innerArr, I did not actually copy its objects but referenced them, so the final arr contains only references to the initial object. So incrementing obj.key affects the initial innerArr object.

The solution is to:

  1. deep copy the innerArr
  2. make changes on the copy
  3. push the copy to arr
  4. start over
const arr = [];
let increment = 0.85;

for (let i = 0; i < 7; i  ) {
    const { id } = object;
    let newInnerArr = JSON.parse(JSON.stringify(innerArr));

    object.newInnerArr.forEach(obj => {
        obj.key *= increment;
    })

    arr.push({
        id,
        newInnerArr
    })
    increment  = 0.05;    // (1:) 0.9, (2:) 0.95...
}

Hope it helps someone :)

  • Related