The value returned from the callback passed to forEach will not be used anywhere.

If you want to avoid mutating the original object and update questions, you can use Array.prototype.map and object spread syntax.

const object = {
  "id": "a8df1653-238a-4f23-fe42-345c5d928b34",
  "webSections": {
    "id": "x58654a9-283b-4fa6-8466-3f7534783f8",
    "sections": [
      {
        "id": "92d7e428-4a5b-4f7e-bc7d-b761ca018922",
        "title": "Websites",
        "questions": [
          { 
            id: 'dee6e3a6-f207-f3db-921e-32a0b745557', 
            ...

const updatedObject = {
 ...object,
 webSections: {
  ...object.webSections,
  sections: object.webSections.sections.map((section, index) => ({...section, questions: newMenu[index]}))
 }
}

If you just want to mutate the original object

object.webSections.sections.forEach((_, index) => {
 section.questions = newMenu[index]
})
Answer from Ramesh Reddy on Stack Overflow
Discussions

How to replace the particular value in array object of nested object with another array object in javascript - Stack Overflow
I have two objects obj1 and obj2, if obj1 property info has keys id and code, If the array object info of obj1 keys code and id matches with obj2, then replace the nos of obj2 with obj1. if not mat... More on stackoverflow.com
🌐 stackoverflow.com
June 29, 2020
javascript - How to change the values of a nested array to all same string? - Stack Overflow
So reassigning element to another value, won't affect the original array. ... Sign up to request clarification or add additional context in comments. ... Save this answer. ... Show activity on this post. This is my solution, a function that iterates through the array and find the nested array which contains * and then replace ... More on stackoverflow.com
🌐 stackoverflow.com
javascript - Replacing all elements in a nested Array - Stack Overflow
In this challenge, I want to replace the integer value that is divisible by two with the string "even" while the rest replaced with the string "odd". /* * - The numbers variable is an array of arrays. * - a nested for loop to cycle through numbers. More on stackoverflow.com
🌐 stackoverflow.com
June 2, 2018
javascript - How to change a value of an object in an array of nested objects - Stack Overflow
I'm trying to loop through an array of objects and if a nested object has a certain value change this value to something else. In this example of dummy data if fruit equals 'plum' change the value ... More on stackoverflow.com
🌐 stackoverflow.com
October 11, 2022
🌐
Stack Overflow
stackoverflow.com › questions › 62629520 › how-to-replace-the-particular-value-in-array-object-of-nested-object-with-anothe
How to replace the particular value in array object of nested object with another array object in javascript - Stack Overflow
June 29, 2020 - match.nos : 0 }; }); } var obj1 =[ { tot: 4, info: [{ id:1, code:"x1", nos:2 },{ id:2, code:"x2",nos:2 }] }, { tot: 2, info: [{ id:3, code:"x3", nos:2 },{ id:5, code:"x5",nos:3 }] } ]; var obj2 = [ { id:1, code: "x1", nos:1, name: "sample1" }, { id:2, code: "x2", nos:2, name: "sample2" }, { id:3, code:"x3", nos:3, name: "sample3" }, { id:4, code: "x1", nos: 0 }, { id:5, code: "x5", nos: 3, name: "sample5" } ]; const res = newArray(obj1, obj2); console.log( JSON.stringify(res).replace(/\},\{/g, '},\n{') ); /* [{"id":1,"code":"x1","nos":2,"name":"sample1"}, {"id":2,"code":"x2","nos":2,"name":"sample2"}, {"id":3,"code":"x3","nos":2,"name":"sample3"}, {"id":4,"code":"x1","nos":0}, {"id":5,"code":"x5","nos":3,"name":"sample5"}] */
Top answer
1 of 2
2

Inside the forEach, you are not really modifying the array. You are passing a value to forEach, corresponding to the values of the nested array. So when you change element's variable value, you are just changing it inside the forEach callback.

There are a few ways to do this... you can go something like this.

    let array = [
        ['A', '*', 'C'],
        ['A', 'B', 'C']
    ]
    
    for (let nestedArray of array) {
        if (nestedArray.includes('*')) {
            for (let i = 0; i < nestedArray.length; i++) nestedArray[i] = '*';
        }
    }
    
    console.log(array);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Or go by using splice if they all have the same fixed size (or even reassign the nestedArray to a ['*', '*', '*']).

Just to be clear: If you have this array: ['a', 'b', 'c']

And iterate it with forEach:

array.forEach(element => ...)

element will have the values 'a', 'b', 'c'. But those are NOT the same 'a', 'b', 'c' of the array. They are copies. So reassigning element to another value, won't affect the original array.

2 of 2
1

This is my solution, a function that iterates through the array and find the nested array which contains * and then replace its values

var grid = [
  ['A', '*', 'B'],
  ['C', 'D', 'E'],
  ['H', 'G', 'F']
]

function changeArr(grid) {
  grid.forEach(arr => {
    if (arr.includes('*')) {
      for (var i = 0; i < arr.length; i++) {
        arr.splice(i, i, '*');
      }
    }
  })
}

console.log(grid);
changeArr(grid);
console.log(grid);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Top answer
1 of 4
2

You used the wrong variable for the row index

myNumbers[column]
//needs to be
myNumbers[row]

Also your if condition is using the wrong row index, and trying to compare against the whole array instead of the value in the array

if(myNumbers[column]%2===0)
//needs to be
if(myNumbers[row][column]%2===0)

Demo

var myNumbers = [
  [243, 12, 23, 12, 45, 45, 78, 66, 223, 3],
  [34, 2, 1, 553, 23, 4, 66, 23, 4, 55],
  [67, 56, 45, 553, 44, 55, 5, 428, 452, 3],
  [12, 31, 55, 445, 79, 44, 674, 224, 4, 21],
  [4, 2, 3, 52, 13, 51, 44, 1, 67, 5],
  [5, 65, 4, 5, 5, 6, 5, 43, 23, 4424],
  [74, 532, 6, 7, 35, 17, 89, 43, 43, 66],
  [53, 6, 89, 10, 23, 52, 111, 44, 109, 80],
  [67, 6, 53, 537, 2, 168, 16, 2, 1, 8],
  [76, 7, 9, 6, 3, 73, 77, 100, 56, 100]
];

for (var row = 0; row < myNumbers.length; row++) {
  for (var column = 0; column < myNumbers[row].length; column++) {
    if (myNumbers[row][column] % 2 === 0) {
      myNumbers[row].splice(column, 1, "even");
    } else {
      myNumbers[row].splice(column, 1, "odd");
    }
  }
}
console.log(myNumbers);

2 of 4
2

Probably easier to use a nested map instead:

var myNumbers = [
    [243, 12, 23, 12, 45, 45, 78, 66, 223, 3],
    [34, 2, 1, 553, 23, 4, 66, 23, 4, 55],
    [67, 56, 45, 553, 44, 55, 5, 428, 452, 3],
    [12, 31, 55, 445, 79, 44, 674, 224, 4, 21],
    [4, 2, 3, 52, 13, 51, 44, 1, 67, 5],
    [5, 65, 4, 5, 5, 6, 5, 43, 23, 4424],
    [74, 532, 6, 7, 35, 17, 89, 43, 43, 66],
    [53, 6, 89, 10, 23, 52, 111, 44, 109, 80],
    [67, 6, 53, 537, 2, 168, 16, 2, 1, 8],
    [76, 7, 9, 6, 3, 73, 77, 100, 56, 100]
];
const output = myNumbers.map(row => row.map(num =>
  num % 2 === 0
  ? 'even'
  : 'odd'
));
console.log(output);

Achieving the same thing with a for loop is much more verbose and confusing, and shouldn't be done in most cases (array methods have better abstraction and don't require manual iteration), but if necessary:

var myNumbers = [
    [243, 12, 23, 12, 45, 45, 78, 66, 223, 3],
    [34, 2, 1, 553, 23, 4, 66, 23, 4, 55],
    [67, 56, 45, 553, 44, 55, 5, 428, 452, 3],
    [12, 31, 55, 445, 79, 44, 674, 224, 4, 21],
    [4, 2, 3, 52, 13, 51, 44, 1, 67, 5],
    [5, 65, 4, 5, 5, 6, 5, 43, 23, 4424],
    [74, 532, 6, 7, 35, 17, 89, 43, 43, 66],
    [53, 6, 89, 10, 23, 52, 111, 44, 109, 80],
    [67, 6, 53, 537, 2, 168, 16, 2, 1, 8],
    [76, 7, 9, 6, 3, 73, 77, 100, 56, 100]
];
const output = [];
for (let rowIndex = 0; rowIndex < myNumbers.length; rowIndex++) {
  const row = myNumbers[rowIndex];
  const newRow = [];
  for (let colIndex = 0; colIndex < row.length; colIndex++) {
    const num = row[colIndex];
    newRow.push(num % 2 === 0 ? 'even' : 'odd');
  }
  output.push(newRow);
}

console.log(output);

🌐
Reddit
reddit.com › r/learnjavascript › changing values of nested arrays
r/learnjavascript on Reddit: Changing values of nested arrays
June 18, 2022 -

This is supposed to be straightforward and I was sure I knew how to do it, but it's not working for some reason. So I have a nested array and I need to convert the values of each nested array to a different value. In my function these are the indices corresponding to values from a different array, but for simplicity's sake let's say I wanna convert them all to 0. So I tried nested loops

let arr =  [[ 1, 0, 2 ], [3, 1, 5]]
  
  for (let indices of arr) {
    for (let i of indices) {
        i = 0
    }
}

console.log(arr)

And the map method

let arr =  [[ 1, 0, 2 ], [3, 1, 5]]
  
function test(arg) {
  for (let x of arg) {
  x.map(e => e = 0) 
  } 
  return arg
  }
  
  console.log(test(arr))

What am I missing? The array isn't being changed. I've been solving a problem since this morning so my brain is fried, this is the last step, any help is appreciated.

Top answer
1 of 4
2
Few thoughts, happy if someone more experienced jumps in too, best not to use 'test' as names for anything. first one the loops arent part of anything - you're just console logging the original array that hasn't been modified, since you never called the for loop. second one just check what you're actually feeding into your map function. instead of calling it on arr, you want to call it on each array in arr, right? curiosity: if you change it to for (let i in indices) and then do indices[i] does it change the result?
2 of 4
2
For the first one, you are looping through each value in the 2D array, and changing the variable i. But, in the for loop, i is just a number, so you set a number equal to 0, it doesn't change the original array. If you wanted to change the og array, you would index it: for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr[0].length; j++) { // Assuming all inner arrays have the same length arr[i][j] = 0; // Or whatever you want } } The map method does not modify the original array, but returns a new one. For example: let x = [1, 2, 3]; let y = x.map(elem => elem + 1); console.log(x); console.log(y); /* Outputs [1, 2, 3] [2, 3, 4] */ // x did not change So you would need to set each inner array equal to the mapped array: function usingMap(arr) { for (let i = 0; i < arr.length; i++) { arr[i] = arr[i].map(x => 0); } } The reason why I used a for loop with i = 0 instead of for (let i of arr) is because the variable (i) gets it's value set to each element of arr, which is [1, 0, 2], then [3, 0, 5]. However, it is not pointing to the original array; it doesn't modify the original array. That's why we need to use the numeric for loop. Also, you could use just a map method: function onlyUsingMap(arr) { return arr.map(inner => inner.fill(0)); } This would allow for different inner-array lengths, but can only set them to 0 in this case. Edit: As u/yokubari said, using function names like "test" aren't good practice, so I renamed them to be a bit more descriptive in my examples
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 72223881 › replace-nested-array-for-new-array › 72224900
javascript - Replace nested array for new array - Stack Overflow
There is a difference between ===, == and =. In this case, you need = ... You can achieve that by using spread operator and without any loop as you want to replace second array with the new array.
Top answer
1 of 2
1

child property represents only one, but this alternative loops the whole array.

You can use recursion to go deeper and updated the found objects by id.

This approach mutates the original array

const allItems = [{  'id': 1,  'text': 'old',  'child': [    {      'id': 2,      'text': 'old'    }  ]}],
      newItems = [  {    'id': 1,    'text': 'new',    'more_info': 'abcd'  },  {    'id': 2,    'text': 'new',    'more_info': 'abcd'  }]
      looper = (arr, items) => {
        arr.forEach(outer => {
          let found = items.find(n => outer.id === n.id);
          if (found) {
            Object.assign(outer, found);
            if (outer.child) looper(outer.child, items);
          }
        });
      };

looper(allItems, newItems);
console.log(allItems);
.as-console-wrapper { max-height: 100% !important; top: 0; }

2 of 2
1

The following will give you some hints on how to approach this problem, without providing the final answer.

Two Approaches

There are two approaches you can take to solve this problem:

  1. Implement a findItemById(id) method that recursively traverses through allItems to find an item with a specific id. Then you can call that function for each entry in newItems and override the relevant properties if you find it.

  2. Implement a traverseItems(itemTree, callback) method that recursively traverses each level of the item tree, and then calls callback with each item and child item it comes across. The callback would then check if that item's ID matches one in newItems and if so, overwrites it's properties with those from the entry in newItems.

Commonalities

If you think about these two approaches, it becomes obvious that the thing needed in both approaches is a recursive traversal function that can go down through all the levels of allItems. So focus on getting that basic algorithm right, and then you can decide between the two. (Hint: one of them is likely to be more efficient than the other, but for small data sets, it really won't matter).

🌐
npm
npmjs.com › package › nested-replace
nested-replace - npm
January 26, 2021 - const input = { a: 'this is a string value', b: [ 'this is a string value inside an array', [ 'this is a string value inside a nested array' ], { c: { d: [ { e: 'this is a string value inside a nested object which is inside a nested array which is inside a nested object which is inside another nested object :)' } ] } } ], }; const newInput = nestedReplace(input, /is/g, 'XX'); // -> newValue = { // a: 'thXX XX a string value', // b: [ // 'thXX XX a string value inside an array', // [ // 'thXX XX a string value inside a nested array' // ], // { // c: { // d: [ // { // e: 'thXX XX a string value
      » npm install nested-replace
    
Published   Jan 26, 2021
Version   1.0.0
Author   Babak Gholamzadeh
🌐
Launch School
launchschool.com › books › javascript › read › arrays
Understand JavaScript Arrays and Common Array Methods with Clarity
It's important to realize that Object.freeze only works one level deep in the array. If your array contains nested arrays or other objects, the values inside them can still be changed unless they are also frozen:
🌐
Stack Overflow
stackoverflow.com › questions › 48481025 › javascript-spread-operator-replace-objects-nested-array-value
Javascript spread operator replace object's nested array value - Stack Overflow
January 27, 2018 - I understand how it is working, but I don't fully understand how the return {...inst, hobbies} syntax functions to update the nested hobbies array. My confusion is due to the fact that when I use hobbies.slice(hobbyIndex,1) instead of hobbies.splice(hobbyIndex,1), my hobbies array does not change event though different hobbyIndex values are being passed in.
🌐
Couchbase Forums
forums.couchbase.com › sql++
Replace object inside a nested array - SQL++ - Couchbase Forums
December 15, 2021 - Hey I have these kind documents: [ { "type": "computer", "defaultProperties": { "characteristics": [ "propertyId": "25e2ed9d-8894-9lc2-55b5-83f36f212p64", "colors": [ { "id": "24e2ed9d-8894-9lc2-55b5-83f36f212f64", "name": [ { "display": "green" } ] }, { "id": "5f124799-001d-2203-aa3e-f3eadff5c8eb", "name": [ { "display": "blue" } ] }, { "id": "fe97b188-1d80-6428-10a...
🌐
Stack Overflow
stackoverflow.com › questions › 44454379 › find-and-replace-in-nested-objects
javascript - Find and replace in nested objects - Stack Overflow
June 9, 2017 - 1 recursive find and replace in multidimensional javascript object · 0 Replacing an object in array · 3 How to add / replace values in a nested object (without losing original references) in Javascript? 1 Iterate over items in object, find matches and replace ·