JavaScript: find all sub-arrays in a given array

I have a complex object structure that I need to simplify:

const test = {
  leagues: [
    {
      timezone: "GMT",
      date: "1/2/2",
      premierLeague: [
        { name: "Liverpool", age: 1892 },
        { name: "Manchester Utd", age: 1878 }
      ],
      laLiga: [
        {
          team: "Real Madrid",
          stadium: "Bernabeu"
        },
        {
          team: "Barcelona",
          stadium: "Camp Nou"
        }
      ]
    }
  ]
};

The goal is to transform it into this simpler result:

const result = [
  { name: "Liverpool", age: 1892 },
  { name: "Manchester Utd", age: 1878 },
  {
    team: "Real Madrid",
    stadium: "Bernabeu"
  },
  {
    team: "Barcelona",
    stadium: "Camp Nou"
  }
];

I attempted using the flat() method but encountered difficulties extracting the arrays within the leagues. The resulting array needs to be dynamic, accommodating all sub-arrays within leagues. Could someone provide guidance on achieving this task?

Answer №1

If the structure of your object doesn't go any deeper, you can use this concise one-liner:

const result = test.leagues.reduce((arr, obj) => Object.values(val).reduce((innerArr, val) => Array.isArray(val) ? innerArr.concat(val) : innerArr, arr), []);

Here is a more readable version:

const result = test.leagues.reduce((arr, obj) => {
  return Object.values(val).reduce((innerArr, val) => {
    return Array.isArray(val)
      ? innerArr.concat(val) 
      : innerArr
  }, arr);
}), []);

Answer №2

Perhaps you are seeking:

const result = test.leagues.flatMap(league =>
  Object.values(league).filter(Array.isArray).flat()
);

Answer №3

This situation feels strange, as you will have objects of various shapes within the same array. How do you plan to handle this?

It appears that your intention is to combine all values from test.leagues that are arrays themselves.

const test = {
  leagues: [{
    timezone: "GMT",
    date: "1/2/2",
    premierLeague: [{
        name: "Liverpool",
        age: 1892
      },
      {
        name: "Manchester Utd",
        age: 1878
      }
    ],
    laLiga: [{
        team: "Real Madrid",
        stadium: "Bernabeu"
      },
      {
        team: "Barcelona",
        stadium: "Camp Nou"
      }
    ]
  }]
};


const output = [];
for (const league of test.leagues) {
  for (const key in league) {
    if (Array.isArray(league[key])) {
      // Add each element in `league[key]` to `output`
      // avoiding the need to flatten it later on
      output.push(...league[key]);
    }
  }
}
console.log({
  output
});

Answer №4

Just wanted to chime in with my thoughts on this topic. I echo the sentiments shared by others. Perhaps this solution will do the trick:

const data = {
  leagues: [
    {
      timezone: "GTM-2",
      date: "20/12/2022",
      premierLeague: [
        { name: "Chelsea", founded: 1905 },
        { name: "Arsenal", founded: 1886 }
      ],
      laLiga: [
        {
          team: "Atletico Madrid",
          stadium: "Wanda Metropolitano"
        },
        {
          team: "Real Betis",
          stadium: "Benito Villamarin"
        }
      ]
    }
  ]
};

let resultArray = [];

function iterateObjects(obj, arrayToAdd) {
    for(const [key, val] of Object.entries(obj)) {
    if(Array.isArray(obj[key])) {
      arrayToAdd.push(obj[key]);
      continue;
    }
    
    const type = typeof obj[key];
    
    if(type === "object") {
       iterateObjects(obj[key], arrayToAdd);
    }
  }
}

iterateObjects(data.leagues, resultArray);

console.log(resultArray.flat())

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

Exploring various properties in React

I'm attempting to render a child component by simultaneously mapping multiple props. My goal is: const Parent = props => { const result = props.(***need to pass both props***).map((firstProp, secondProp) => ( <Child key={//} ...

Locally hosted website failing to transfer login details to external domain

Having trouble with an ajax call that is supposed to retrieve data from a web page, but instead returns a jQuery parse Error. Even though I can access the page directly, the ajax call doesn't seem to be working and storing the result properly. Below ...

Empty Media Viewer

I am encountering an issue with setting up a code, as it only displays a blank white page. Any suggestions on what might be causing this problem in the setup and assistance in resolving it would be greatly appreciated. <script type="text/javascript ...

What could be causing the removal of style classes from my element after it is appended?

Could you please explain how it functions? I am attempting to append a div with content using innerHTML and it is working, but without any of the styling classes being applied. const element = document.createElement("div"); element.classList.add("col ...

Introducing a custom JavaScript function using Selenium in Java

I am faced with the challenge of incorporating a dynamic function after the page has loaded. This need arises because the function name is dependent on a variable obtained through parsing HTML. Presently, my approach involves: Context: Using Selenium 3.3. ...

Is there a way to pass the state to the page destination when navigating back in the browser using react-router-dom?

Using react.js and react-router-dom, I have created two pages: Form.js, where you enter your name in a form, and Confirmation.js, where you confirm the name. I am trying to share the state between these two classes so that when you switch to another page u ...

jquery mobile page navigation option

I am a big fan of the navigation system in jQuery Mobile: <a href="page-transitions-page.html" data-transition="slidedown" class="ui-btn ui-corner-all ui-shadow ui-btn-inline">page</a> () It is incredibly user-friendly, and I really enjoy th ...

react component fails to rerender upon state change

I am struggling with a React functional component that includes a file input. Despite selecting a file, the text in the h1 tag does not change from choose file to test. The handleChange function is triggered successfully. A console.log statement confirm ...

Having difficulty with TypeScript typings implementation

Update: I have revised the post to provide a clearer explanation of the steps I have taken and the challenges I am encountering Initially, I created a basic html/js page. I also implemented xregexp from a cdn. var reg = XRegExp("^lights:(?<option> ...

Populate a dropdown with values from a JSON object

There is a function in my code that retrieves JSON text from a specific website: window.onload = function httpGet() { var xmlHttp = null; var box = document.getElementById("http") //just for testing xmlHttp = new XMLHttpRequest(); xmlHttp. ...

Error Occurs While Getting Request Parameters with Ajax Post and Express.js

When utilizing ajax to send data from a JavaScript frontend to an Express.js backend server, I am having trouble retrieving the posted data in the API method of my express.js. Below is the code where I attempt to parse the request data. Your assistance i ...

Transmitting a JSON array from a client-side using AJAX to a server

I am currently working on sending a JSON array to PHP. I have successfully sent the data but am facing some challenges when it comes to parsing it. Below is the code snippet that I am referring to: JavaScript: var employees = [ { "firstName":"John" , ...

Can the angularjs cached resource method be utilized within a filter?

In my current project, there is a property in the scope that contains an ID for an external object. Additionally, I have implemented a filter that takes this ID and expands it into a complete object using the following code: {{ typeId | expandType }} Fil ...

Trouble with callback execution during async foreach loop when using collection.save() in Node.js

In my quest to store records in a mongoDB collection while in an async foreach loop, I encountered an issue where the code seems to be skipping the save part altogether. Here is the relevant snippet: async.forEach(data, function(item, callback) { va ...

The performance of dom-repeat may be impacted when dealing with sizable objects, such as those containing base64 encoded images

Currently, I am encountering an issue while generating a dom-repeat using a list of objects. Each object in the list has an imgUrl key containing a large base64 encoded image. However, when I generate the dom-repeat in this manner, each item appears undef ...

I encounter Error 406 and CORS issues when making API calls

I am currently engaged in a project aimed at helping my employer keep track of shipping loads, customers, carriers, and locations. The frontend is built using a react app that enables users to input information regarding loads, customers, etc. On the backe ...

What is the best approach for assigning initial values to data retrieved from Vuex?

My objective is to develop an 'edit account' form where users can update their account details. I aim to display the account information in a pre-filled form that includes fields like username, email, and address. Users will be able to make chan ...

Is there a way to adjust the height of one div based on the height of another div in Bootstrap?

I am experimenting with a Bootstrap example featuring a table in the left column and 4 columns in 2 rows in the right column. Check out the code below: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css ...

Upgrading from Asp.Net Core 2 to .Net 6 caused issues with XMLHttpRequest for me

Hello everyone, I recently upgraded my ASP.Net Core 2 MVC app to .Net 6, and ever since then, I've been experiencing a strange issue. The XMLHttpRequest responses I receive are always empty, showing "{}" or [{},{},{},{}] for arrays, even though the ba ...

Is there a method to enclose a Grafana row with a border?

I recently created a Grafana dashboard using JavaScript and I realized that adding a border around each row would enhance readability. Here is how the current view looks like: https://i.stack.imgur.com/itKYR.png However, it can be difficult to differenti ...