Swap out the old nested array for a fresh array

Currently, I am dealing with an array nested inside another array. The structure looks like this:

Structure:

First Array
[
{
Second Array
   [
     {
     }
   ]
}
]

I am attempting to replace all instances of Second Array with a new array that I have created. This is what I have tried so far:

this.FirstArray.map(
          (myArray) =>
            myArray.SecondArray === this.MyNewArray
        )

However, despite my efforts, the old values are still present and my new array has not replaced them. What could I be doing wrong?

Answer №1

To achieve this, you can make use of the spread operator instead of any looping mechanism. This will allow you to replace the second array with the new one without traversing through each element individually.

Here is how the input array looks like:

First Array
[{
  Second Array
   [{}]
}]

The logic to swap out newArray with secondArray is as follows:

FirstArray[0].secondArray = [ ...newArray ]

Check out this demo for a better understanding:

const firstArray = [{
    secondArray: ['alpha', 'beta', 'gamma']
}];

const newArray = ['A', 'B'];

firstArray[0].secondArray = [ ...newArray ];

console.log(firstArray);

Answer №2

Typically, when you use the map() method, it generates a fresh array.

// Let's say your multi-dimensional array looks like this:
let nestedArray = [
    ["X", "Y", "Z"],
    ["J", "K", "L"]
]

// This is the new array
const newArray = [4, 5, 6]

nestedArray = nestedArray.map(item => newArray);

// expected result: nestedArray [[4, 5, 6], [4, 5, 6]]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

increasing the size of a picture without resorting to a pop-up window

Struggling to implement a product details tab within a table that features a clickable image. When the image is clicked, it should enlarge but the width doesn't adjust accordingly. I'm using bootstrap 5.3 and can't seem to identify the root ...

Parsing the JSON string from PHP using JSON.parse resulted in an unexpected and strange array

I've encountered a challenge when trying to transfer a JSON object from the server to client-side JavaScript. I fetched rows of data from a MySQL query and stored them in $result. Below is the code snippet: var json = '<?= json_encode($resu ...

Ensure consistency across browsers by disabling zoom functionality on touchpad inputs while still permitting scrolling actions

I am looking for a way to disable 2-finger zoom on trackpad "wheel" events while still allowing 2-finger scroll. On mobile, I have already disabled zoom with: <meta name="viewport" content="initial-scale=1, minimum-scale=1, m ...

Angular4 and jQuery working together for effective navigation and pagination

Trying to implement pagination in angular 4 and jQuery, but encountering an issue where clicking on the next button causes it to skip through multiple pages at once (2, then 3, then 5)... Component code: addClass(x) { $(".page-item").click(function () ...

How can I effectively utilize find, match, and filter functions with a reactive array in VueJS?

Having some trouble with understanding .value! :) I'm currently working with VueJS v3 and the Composition API. My goal is to locate the first matching value in a reactive array of people. Typically, this array would be populated through an API call, ...

Vue.js encountered an issue: Conflict Error - Multiple assets are emitting different content to the same file name index.html

Upon creating a new vue.js project on my MacBook and running "npm run serve", I encountered the following error. No changes have been made to any files since the project was created. markus@Markuss-MBP meinerstesprojekt % npm run serve > <a href= ...

Convert HTML code into a customized JSON structure

Is there a way to convert HTML into a specific JSON object? For instance This HTML page is well-structured (originally in markdown). I am interested in creating a JSON version of the different sections present on the page. In this scenario, every "h2" s ...

Is there a way to retrieve the Response object in Express from outside the Route

Currently, my backend API is built using Express JS. Instead of using the res object directly in the route controller, I am looking to access it from a custom service. While I know that I can simply pass res as an argument to the service function and use ...

Show the template when the link is clicked using Angular directive

Perhaps the question is not phrased properly, but here is the idea I am working on. I have a navbar set up with an array of countries that includes their names and coordinates. <body> <nav class="navbar navbar-default"> <div cl ...

Executing a Javascript function repeatedly

Here is a sample JavaScript function: function f1() { alert("HI"); } I have two different locations where I am calling the same JavaScript function: <input type="submit" id="btn1" onclick="f1()"/> <input type="submit" id="btn2" onclick="f1 ...

Creating an array of custom objects in JavaScript.Initializing custom objects in an

Is there a proper way to prevent the error "Cannot read property 'length' of undefined" when initializing an array of custom objects in javascript? situation export class MyClass implements OnInit { myArray: MyObject[]; } example <div ...

Looking for assistance on how to automatically close the sidebar or pull navigation menu after clicking on a menu item

My website is designed to be responsive and includes a navigation slider that is hidden off-screen by default. The slider features a vertical push/pull bar that remains visible for users to access the menu. The entire navigation slider is fixed on the page ...

AngularJS: Refresh array following the addition of a new item

After saving an object, I am looking to update an array by replacing the conventional push method with a custom function. However, my attempts have not been successful so far. Are there any suggestions on how to rectify this issue? app.controller("produ ...

Execute a multer request to upload an image (using javascript and express)

I am utilizing the Express server as an API gateway for my microservices, specifically to process and store images in a database. The issue at hand is that within the Express server, I need to forward an image received through a POST request from the clien ...

Encountered an issue while executing Jest test with vuejs-datepicker

Currently, I am diving into the world of Jest while testing my Vue application. Everything was going smoothly until I encountered an issue with one of my components that utilizes vuejs-datepicker. Whenever I run the tests below, I consistently encounter an ...

Ways to implement form validation with JavaScript

I'm currently working on a project for my digital class and I'm facing an issue with my booking form. I have two functions that need to execute when a button is clicked - one function validates the form to ensure all necessary fields are filled o ...

Struggling with modifying class in HTML using JavaScript

I've been attempting to replicate a JavaScript code I came across on the internet in order to create a functioning dropdown menu. The concept is quite straightforward - the div class starts as xxx-closed and upon clicking, with the help of JavaScript, ...

Root location for offline and pre-production in the Backbone boilerplate router

I am currently utilizing the backbone boilerplate found at https://github.com/tbranyen/backbone-boilerplate My development process involves working on static HTML/JS files offline and conducting tests offline before deploying them to another site for pre- ...

The status of "Checked" has now been set to untrue

As a beginner, I am struggling to understand how the value changes in my code. Here is a screenshot of the Material UI switch: In the provided code snippet, the value event.target.checked is coming from the following Switch component: <Switch c ...

When using Thunderbird Webextensions, calling .messages.getFull() may result in the Exception 0x80004005 being raised, specifically indicating

This question is a follow-up to a previous question/answer found at: In this scenario, the code attempts to retrieve a list of accounts, select the emailAccountName, get a MessageList object from the specified wantedMailFolderType, and then access a Messa ...