Carlos Miguel Colanta Carlos Miguel Colanta - 4 months ago 7
Javascript Question

nested forEach doesn't change its elements

This is what I'm trying to do:

enter image description here

I get no error after I executed the script but no changes or whatsoever is being made.

This is my JSON Object that is stored in

doc


{
"name":"aaa"
"test":[
{ "carl":[
"huh",
"two"
]
}
]
}


This is the script that I am running:

doc.test.forEach(function(emp){
emp.carl.forEach(function(pass){
pass="change";
});
});


but no changes are being made or whatsoever, What is wrong?

Expected output: change all elements inside
carl
to
changed
. all
test
elements will contain a property
carl
that contains an array of string.

Answer

Assigning a parameter to some value won't have any effect outside that function.

Instead, you should assign a property:

emp.carl.forEach(function(pass, i, arr){
  arr[i] = "change";
});

var doc = {
  "name": "aaa",
  "test": [{
    "carl": [
      "huh",
      "two"
    ]
  }]
};
doc.test.forEach(function(emp) {
  emp.carl.forEach(function(pass, i, arr) {
    arr[i] = "change";
  });
});
console.log(doc);

Comments