Combining arrays of objects using JSON format in JavaScript

Here is an example of a JSON file:

[
  {
    "stores": [ 
        {
          "name" : "My store",
          "location" : "NY"
         },
         { 
          "name" : "Other store",
          "location" : "FL"
         },
         {
          "name" : "My other store",
          "location" : "NY"
         }
     ],
  },
  {
    "stores": [ 
        {
          "name" : "Another My store",
          "location" : "NY"
         },
         { 
          "name" : "Some Other store",
          "location" : "FL"
         },
         {
          "name" : "Secondary store",
          "location" : "NY"
         }
     ],
  }
]

The goal is to combine the data into one single array:

[
        {
          "name" : "My store",
          "location" : "NY"
         },
         { 
          "name" : "Other store",
          "location" : "FL"
         },
         {
          "name" : "My other store",
          "location" : "NY"
         },
         {
          "name" : "Another My store",
          "location" : "NY"
         },
         { 
          "name" : "Some Other store",
          "location" : "FL"
         },
         {
          "name" : "Secondary store",
          "location" : "NY"
         }
]

I am currently working on a loop to achieve this, but I am unsure how to group all the items together:

const input = [
  {
    "stores": [ 
        {
          "name" : "My store",
          "location" : "NY"
         },
         { 
          "name" : "Other store",
          "location" : "FL"
         },
         {
          "name" : "My other store",
          "location" : "NY"
         }
     ],
  },
  {
    "stores": [ 
        {
          "name" : "Another My store",
          "location" : "NY"
         },
         { 
          "name" : "Some Other store",
          "location" : "FL"
         },
         {
          "name" : "Secondary store",
          "location" : "NY"
         }
     ],
  }
];

let grouped = []
input.forEach(item => {
    const store = Object.keys(item.stores)
  console.log(store)
})

Answer №1

Utilize the Array#flatMap() method:

function combineStores(array) {
  // Transform each element to its 'stores' array, then flatten all of them
  return array.flatMap(element => element.stores);
}

Give it a go:

console.config({ maximize: true });

function combineStores(array) {
  return array.flatMap(element => element.stores);
}

const input = [
    {
        stores: [
            { name: 'My store', location: 'NY' },
            { name: 'Other store', location: 'FL' },
            { name: 'My other store', location: 'NY' }
        ]
    },
    {
        stores: [
            { name: 'Another My store', location: 'NY' },
            { name: 'Some Other store', location: 'FL' },
            { name: 'Secondary store', location: 'NY' }
        ]
    }
];

console.log(combineStores(input))
<script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

Answer №2

const storesData = [
  {
    stores: [
      {
        name: "Best Buy",
        location: "CA",
      },
      {
        name: "Target",
        location: "TX",
      },
      {
        name: "Walmart",
        location: "NY",
      },
    ],
  },
  {
    stores: [
      {
        name: "Apple Store",
        location: "CA",
      },
      {
        name: "Home Depot",
        location: "TX",
      },
      {
        name: "Costco",
        location: "NY",
      },
    ],
  },
];

// Initialize the result array with an empty `stores` property
const result = [{stores: []}]
// Iterate through each object in the storesData array
storesData.forEach(object => {
  // For each object, retrieve the `stores` property and 
  // append its contents to `result[0].stores`
  result[0].stores.push(...object.stores);
})
console.log(result);

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

Children can easily access multiple items within a list by using the ul tag

I am struggling with changing the class of ul inside the ul.navigator. I want to change it only when I click on a particular li, but my current approach doesn't seem to be working. Can anyone provide some guidance or assistance? $('.navigator& ...

Ways to circumvent ng switch and create a component based on type

In my current code, I have an array called resourceTypes and I am using ngSwitch to create different components/directives based on the TypeName. However, I find this approach cumbersome as I have to update the code every time I add a new resource editor. ...

Notification of array being converted to a string

I'm encountering a puzzling notification on the specific line of code below: $this->$aStyles = $aStyles; This particular code snippet is within the following function: private function cleanStyles() { if ((isset($this->sValue))&&( ...

A simple way to deactivate a React component (or the onClick event itself) using the onClick event

I have come across similar inquiries, but unfortunately, none of the solutions provided seem to work in my particular scenario. I am hopeful that someone can shed some light on what might be causing the issue. In my ReactApp, there are 3 card components t ...

Data is successfully being stored in an array in AngularJS, however, it is not appearing in the user interface

Having an issue with displaying updated data on my UI. I am successfully pushing data into the database and an array using Angular 2-way binding. The data is being pushed as confirmed by the console, but it's not showing up on the user interface. Con ...

What could be the reason for Object.assign failing to update a key in my new object?

Function handleSave @bind private handleSave() { const { coin, balance } = this.state; console.log('coin', coin); console.log('balance', balance); const updatedCoin = Object.assign({ ...coin, position: balance }, coi ...

JSON data parsing error: The field "item" does not contain a value

I encountered a JSONException with the message "No value for {"username":"sara"}{"username":"john"}" when trying to retrieve data from a MySql database using an Android app. 08-20 04:26:39.396: W/System.err(4732): org.json.JSONException: No value for {" ...

Guide to setting up a backend system using AJAX, PHP, and MySQL to handle dynamic video sources in conjunction with Google TV Templates

If you're looking to develop web apps for Google TV, particularly those involving video content, the simplest method is to utilize Google TV Templates: https://developers.google.com/tv/web/docs/gtv-templates. The original Google TV Templates included ...

Exploring threejs to project onto a cylindrical surface

Can you provide guidance on how to project an image onto a cylinder using threejs? Do I need to map separate portions of the image onto each face of the cylinder, or is there a more efficient method available? Appreciate any help on this matter! ...

Tips for adjusting image hues in Internet Explorer?

I have successfully altered the colors of PNG images in Chrome and Firefox using CSS3. Here is my code: #second_image{ -webkit-filter: hue-rotate(59deg); filter: hue-rotate(59deg); } <img src='http://i.im ...

Next.js- The requested resource is missing the 'Access-Control-Allow-Origin' header

Recently, I took over a legacy Next application that was converted from React. On a particular page that requests data from an AWS server, I encountered a CORS error - Access to XMLHttpRequest at 'https://**************' from origin 'http:/ ...

Tips for verifying the input field with specific requirements in Angular 6

There is an input field that needs to validate text based on certain logic conditions: No spaces should be allowed in the formula. The operators (and,or) must be lowercase and enclosed in curly brackets {}. The number of opening '(&apos ...

Modifying the color of a header through clicking on a specific anchor link

My goal is to create a fixed side nav bar on my webpage with an unordered list that links down the page using anchors. In addition, I want to dynamically change the color of an h2 element based on which item in the fixed nav bar is clicked on. For instan ...

In the world of web development with JavaScript, jQuery, and EasyUI, we often encounter situations where the parameter

function formatData_original() { // convert obj_num2.formatter = function(value, rec) { var baseStr='&nbsp;&nbsp;' + rec.s_date + '<a class="easyui-linkbutton" href="javascript:void(0);" plain= ...

Add a variable from a callback function in AJAX's success response

Is there a way to effectively utilize the variable in the appended message of the AJAX success call? http://codepen.io/anon/pen/fdBvn data['name'] = $('#goofy').val(); $.ajax({ url: '/api/1/email/test/', data: data, type ...

What is the proper way to configure QuoteName settings in Json.Net?

Initially, I am aware that the JSON format supplied is not valid. However, due to my customer web service configuration requirements, I am in need of setting QuoteName of Json.Net JsonTextWriter to false. Unfortunately, I am uncertain of the correct method ...

Refusing to cease downloading music on the local server through the embedded audio element

I was trying to setup background music on my website, but when I test it localhost, the music download instead of playing. However, when I tested with the full path, it played as expected. How can I prevent the download from happening in localhost? Here i ...

Transform the jQuery Mobile slider into a jQuery UI slider and update the text

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script> function modifycontent() { if (document.getElementById("slider").value<33) { $("#1").fadeIn("slow"); $("#2").fadeOut("slow"); ...

Serializing a JSON object to a C# class

Currently, I am tackling the task of deserializing a Json Object into a class in .NET Visual Studio 2015 on Windows 7. public class1 { [JsonProperty(TypeNameHandling = TypeNameHandling.Objects)] public Class1 data1; public Class2 data2; } pub ...

Locate XML attribute in VS code and substitute it with the product of the current value and a

Editing a massive XML file with numerous contents can be quite time-consuming. Is there a feature available in editors like VS Code that allows users to specify a field and then multiply it by a certain value? This would significantly speed up the editin ...