简体   繁体   中英

Original array not getting updated when changed in referenced variable

For my work, I need to access nested object array. I do not want to access it every time with full path. So I wanted to shorten the reference by assigning the actual reference to a variable.

I tried to find out existing answers, but didn't get answer for this scenario.

What I have done: Assigned the reference of array to a variable, modified the referenced value. But the original array is not getting modified.

Below is a demo code for what I want to achieve.

 let obj = { innerObj1: { arr: [2,3,4,5,6] } } var ref = obj.innerObj1.arr; console.log(ref); // output [2,3,4,5,6] ref = ref.filter(n => n%2 == 0); console.log(ref); // output [2,4,6] //Original obj console.log(obj.innerObj1.arr) // output [2,3,4,5,6]

Just access specific indices within ref :

let obj = {
    innerObj1: {
        arr: [2, 3, 4, 5, 6]
    }
}

const ref = obj.innerObj1.arr;
console.log(ref);
// output [2, 3, 4, 5, 6]

for(let i = 0; i < ref.length; i++) {
  ref[i] = ref[i] % 2 == 0;
}

// Original obj
console.log(obj.innerObj1.arr)
// output [true, false, true, false, true]

when we do

var ref = obj.innerObj1.arr;

we are having a pointer to obj.innerObj1.arr ref is reference to array when we do ref.filter(n => n%2 == 0);

to get what we want we have to do

obj.innerObj1.arr = ref.filter(n => n%2 == 0);

This is because filter method returns a new array and you are overriding it with the new value.

As stated earlier it creates a new array, it means ref variable is not referring to old array anymore. It is referring to new array created by filter method.

You can simply use for, while or do while loop to resolve your this issue.

I hope it will help you. Please find working example here:

 let obj = { innerObj1: { arr: [2,3,4,5,6] } } var ref = obj.innerObj1.arr; console.log(ref); // output [2,3,4,5,6] for(let index=0; index < ref.length; index++) { if(ref[index] % 2 === 0) { ref[index] = ref[index] } else{ ref.splice(index,1); } } console.log(ref); // output [2,4,6] //Original obj console.log(obj.innerObj1.arr) // output [2,3,4,5,6]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM