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

using java to invoke a server-side function within a mapReduce operation in mongodb

i have saved two functions in the "system.js" collection under the names "mapfun" and "reducefun" and now i am attempting to invoke these functions from Java. I am trying to utilize MapReduceCommand for this purpose but encountering difficulties in calling ...

Switching between Custom tooltips and default tooltips in Chart.js and Angular

I need to show a tooltip based on certain conditions options: { tooltips: if (tooltipCondition === true) { { mode: 'index', position: 'nearest' } } else { { enabled: false, custom: function (tooltipMo ...

Creating a multi-dimensional array in JavaScript with two different sizes

I'm struggling to find the best way to create a multi-dimensional array with varying sizes dynamically. Our user interface requires a pattern where there are rows of 4 items followed by rows of 3 items. This pattern should continue until all contents ...

When using res.json(), the data is returned as res.data. However, trying to access the _id property within it will result

I'm facing a challenge in comprehending why when I make a res.json call in my application, it successfully sends data (an order object). However, when I attempt to access and assign a specific piece of that data (res.data._id) into a variable, it retu ...

I am having issues with the functionality of vuejs's this.$route

When I send a delete request to the API, it works fine. However, the next step is redirecting to the index page. I tried using this code this.$router.push('/'); but it doesn't seem to be working. index.vue <template> <div cl ...

Why does tsc produce a compiled file that throws an exception when executed, while ts-node successfully runs the TypeScript file without any issues?

I have written two ts files to test a decorator. Here is the content of index.ts: import { lockMethod } from './dec'; class Person { walk() { console.info(`I am walking`); } @lockMethod run() { console.info(`I am running`); } ...

VueJS intricate v-if condition

Is there a way to display a button only if two specific conditions are met? I attempted to use v-if with one condition at a time: v-if="editMode" v-if="$can('customersdelete')" When using only one condition at a time, the button displays. This ...

Sort through various table columns

I am currently utilizing a data table component from Framework7, which is being generated dynamically with JSON data. My goal is to make the column filter input functional within the table. So far, I have succeeded in implementing the filter for the first ...

Unable to locate the module named '@/components/HelloWorld.vue' or its associated type declarations. Error encountered in Vetur(2307)

After creating a new project using the vue command line tool with "vue create .", I encountered an issue when trying to run "npm serve". The component import is showing up as red, even though I haven't made any changes to the project yet. The error m ...

VueJS throws an error indicating that the object cannot be extended

I have encountered an issue while trying to update the promo object by adding a new field called colspan. Unfortunately, I am getting this error: uncaught (in promise) TypeError: Cannot add property colspan, object is not extensible at eval (eval at ...

What is the best way to partition JSON data from an API request in React and display it in various sections within the component

There are 2 JSON objects that contain sales period details based on Month to date and year to date. The data includes information such as Units Sold, Gross Revenue, Year to Date Totals, Month to Date Averages, Expenses, Net Revenues, and Per Unit values. I ...

Show nested arrays in Vue.js exhibition

As a newcomer to vue, I've been navigating my way around with some success. Lately, I've been dealing with JSON data structured like this: [ { "name": "jack", "age": "twenty", "Colors&qu ...

Issues with zoom functionality not functioning properly within IE11

I am currently developing an application with Angular that is designed to be compatible with tablets and touch-enabled devices. One of the key features I want to implement is the ability for users to zoom/scale up the app, especially for those with visual ...

The port has not been defined

My Node server appears to be operational, however the console is displaying an error message stating that the port is undefined. const express = require('express'); const env = require('dotenv') const app = express(); env.config(); ap ...

Rails: Ensure that JSON form fields remain populated in case the form encounters a validation error

I am using a rails simple form to create a product with three fields inside in order to associate it with appropriate categories: <div class="form-group"> <%= f.input :child_category_id, :collection => @categories.order(:name), :l ...

Unlocking the power of setting global variables and functions in JavaScript

Within my language.js file, the following functions are defined: function setCookie(cookie) { var Days = 30; //this cookie will expire in 30 days var exp = new Date(); exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000); document.cookie = coo ...

What is the process of invoking Link manually in React-router?

I am working on a component that is passed a <Link/> object from react-router as a prop. When the user clicks on a 'next' button within this component, I need to manually trigger the <Link/> object. Currently, I am using refs to acce ...

The image file that was uploaded from a React Native iOS application to Azure Blob Storage appears to be corrupted or incomplete as it is not

Struggling to develop a feature in a React Native mobile app where users can upload and crop their profile picture, then store it in Azure blob storage. I encountered difficulty with implementing react-native-fs as many resources recommended it, but I kep ...

Issue with konvaJS when trying to simultaneously resize, drag, and apply filters to an image

Looking for help with resizing, dragging, and filtering images using Konvajs 2d canvas library? If the images are not resizing properly after applying a filter, can someone assist me? Note: Please be aware that when using Google image URLs, there may be c ...

The ES6 method of binding click handlers with parameters in React

After reading numerous articles on the usage of () => {} syntax, binding in the constructor, and binding in the props, I have come to understand that binding this can be performance-intensive. Furthermore, automatic binding with arrow functions incurs a ...