Adding an object array to a new array - Step by step guide

I am working with an array of states

const states = [{id:1,name:"New York",cities:[...]},{id:2,name:"California",cities:[...]}]

My goal is to extract all cities and store them in a new array using methods

...

const cities = []

this.states.forEach((state, index, array) => {
   this.cities = [...state.cities]
});

console.log(this.cities)
...

The issue I am facing is that only the last set of cities (California) is being retrieved. How can I resolve this problem?

Answer №1

Consider utilizing the flatMap method as shown below.

this.cities = this.states.flatMap(s => s.cities);

Take a look at the example below.

const states = [{
  id: 1,
  name: "New York",
  cities: ['A', 'B']
}, {
  id: 2,
  name: "California",
  cities: ['C', 'D']
}];
let cities = states.flatMap(s => s.cities);
console.log(cities);


Alternatively, you can also use the approach mentioned in your question. The issue was that your cities object was being overwritten by each states.cities. To prevent this, modify your code as follows to include both current and new values of cities.

this.cities = [...this.cities, ...state.cities];

Note: Re-assigning the value as above will not work with const. Make sure to declare cities with let. Alternatively, you can use .push like

this.cities.push(...state.cities);
, which works with both const and let.

const states = [{
  id: 1,
  name: "New York",
  cities: ['A', 'B']
}, {
  id: 2,
  name: "California",
  cities: ['C', 'D']
}];

let cities = []
states.forEach((state, index, array) => {
  // Uncomment the following line if declaring cities as const causes issues
  //cities = [...cities, ...state.cities];
  
  // Use .push if working with const variables
  cities.push(...state.cities);
});
console.log(cities);

Answer №2

Make sure to avoid overriding previous values by using the push method within your forEach loop when assigning new cities.

this.cities.push(...state.cities)

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

Is it possible in Vuetify 2 to align the items within the expansion of a v-data-table with the headers of the main component?

I am currently working on rendering a v-data-table where the expandable section serves as a "panel" title and I want the data inside the expansion to align with the headers set at the root level. Despite my efforts, I have not been able to find a way in th ...

What is the best way to utilize MongoDB aggregate in this particular scenario?

How can I optimize this mongoose query to improve performance and reduce size for production? const currentYear = (new Date).getFullYear() const usedCars = await CarModel.find({ ModelYear: {$lte: currentYear - 1} }).limit(10) const recentCars = await Car ...

Determine the upcoming Saturday's date by utilizing a stored procedure in Snowflake

Looking for assistance in retrieving the upcoming Saturday date based on a date field in a table using a Snowflake JavaScript stored procedure. Any suggestions would be greatly appreciated. Running the following query in the Snowflake console provides the ...

Tips for updating a specific field within an object in an array within a mongoose schema and persisting the changes

I am currently developing a website where users can sign in, create tasks, and mark them as done. I am using mongoose to work with the data, specifically saving tasks inside an array of type Task in a User model. Each task has a "done" value which is repre ...

Alter the DOM element every ten seconds

Is there a way to modify a DOM element every 10 seconds? I attempted the following approach: var endurance = angular.element('.progressbar').height(); var endurance2 = angular.element('.progressbar').css('height', endurance- ...

Serialization of forms consistently yields an empty string

In my view, I have a dropdown menu that triggers the insertion of a partial view into a designated div when an option is selected. The following code snippet demonstrates what the view looks like: <div class="container"> <div class="row"> ...

What could be the reason behind ng-bind-html only displaying text and not the link?

Utilizing ng-repeat to exhibit a list on my webpage. One of the fields in my data contains a URL that I want to display as an actual link within my HTML page. Please refer to the screenshots below: My HTML: https://i.sstatic.net/2Gj1U.png My rendered pa ...

Interactive game created using JavaScript input

I've scoured the internet for guidance on creating a text-based game that utilizes user input, but all I come across are tutorials focusing on button interactions. What I envision is triggering different responses based on specific user inputs. For i ...

Improving a Vue.js notification component with data retrieved from a fetch request result

Struggling with updating the content inside a vuetify v-alert. There's an issue when trying to update Vue component properties within the sessionID.then() block after logging into a system and receiving a session id. Vue.component('query-status ...

Combining properties of JavaScript objects into one

Just starting my Vue journey and encountering a slight challenge. Displayed below is a table with various items: Whenever an item is selected and its quantity increased, I need my addOptional method (optional) to update a variable with the item's qu ...

The backend of Asp.net core 3.1 is unable to retrieve the Identity stored in the cookie

I am encountering an issue with my application that has a vue.js frontend and asp.net core 3.1 backend. The backend utilizes SignInManager and Identity with cookie authentication. Strangely, API requests work perfectly fine when made from Postman, roles ar ...

Why is TinyMCE removing my custom MPDF HTML elements?

I have a Vue application with a Symfony backend. I am using TinyMCE to edit documents that are generated by mpdf. In the mpdf twig content, I need to add a page footer on certain pages and exclude it on others. To achieve this, I have created custom HTML t ...

Error: Unable to locate module during module creation

I encountered an error while trying to import a module in my test application. ../fetchModule/index.js Module not found: Can't resolve './Myfetch' in '/Users/******/nodework/fetchModule' Here is the folder structure: https:/ ...

Accessing form data from Ajax/Jquery in php using $_POST variables

Thank you in advance for any assistance on this matter. I'm currently attempting to utilize Ajax to call a script and simultaneously post form data. While everything seems to be working correctly, the $POST data appears to come back blank when trying ...

Vue project experiencing issues with font-awesome integration

To incorporate Font Awesome icons into my Vue project, I followed these steps. Initially, I added the Font Awesome library to my project. npm install font-awesome --dev-save However, after installation, the icons did not display properly - instead, showi ...

What is the best way to transpile when using vue-cli-service to build a library?

Currently, I am in the process of creating a library primarily consisting of .vue components for reusability across various projects (not intended for public npm use) using vue-cli-service. Everything appears to be set up correctly, and I can confirm that ...

Vue components not being highlighted within template section of Visual Studio Code

I previously had all my imported components within the displayed in a special color compared to other traditional HTML components. However, this feature no longer seems to be functioning. I have already attempted uninstalling and reinstalling all extensi ...

Improving React efficiency: What techniques can be used to prevent the entire component from re-rendering every time a prop changes?

Issue at Hand I created a custom component named PageLayoutSideBar.tsx that accepts two props: sideBar and content. This component is designed to make it easy to display the sideBar and page content with the appropriate styling and sidebar width. My conce ...

Transforming conversion code snippet from jQuery to Dojo - utilizing AJAX techniques

I am in the process of converting my code from jQuery to Dojo. I just need an equivalent snippet that works. The jQuery code is functioning properly, but the Dojo code is not working as expected. JQUERY <script type="text/javascript"> $(docume ...

React not displaying wrapped div

I am facing an issue with my render() function where the outer div is not rendering, but the inner ReactComponent is displaying. Here is a snippet of my code: return( <div style={{background: "black"}}> <[ReactComponent]> ...