Guide to flattening a nested array within a parent array using lodash

Within my array named sports, there is another array called leagues, but I need to flatten these arrays using _.flatten due to issues with Angular filters.

If you look at the data, inside the first array which contains a "name":"Live Betting", there is another array named "leagues" that needs to be flattened.

[
  {
    "id": 26,
    "name": "LIVE Betting",
    "priority": 0,
    "leagues": [
      {
        "id": 3042,
        "parent": 1000,
        "name": "LIVE BETTING - NBA",
        "sport": {
          "id": 26,
          "name": "LIVE Betting"
        },
... 

Furthermore, the resolver with a promise is returning that array, which is retrieved by Sports.

      resolve: {
        Sports: function(SportsFactory, AuthFactory, $q) {
          var defer = $q.defer();
          AuthFactory.getCustomer().then(function(customer) {
            SportsFactory.getSportsWithLeagues(customer).then(function(sports) {                  
              defer.resolve(sports);
            });
          });
          return defer.promise;
        }
      }

Here is the controller where I invoke the resolver Sports.

  .controller('SportsController', function($scope, AuthFactory,
               SportsFactory, Sports) {
    console.log(angular.toJson(Sports, 'pretty'));
    $scope.sports = [];
    $scope.sportPromise = Sports;

For easier checking, you can access the Plunkr here: http://plnkr.co/edit/FJ45nV6gdwp3SkRglPeW?p=info

Answer №1

It seems you might be looking for a solution that involves creating a flattened array in your controller. Here's a possible approach:

Start by defining a function in your controller that generates the flattened array:

 $scope.flattenLeagues = function(){
  var allLeagues = [];
  _.each(mySports, function(sport){
    allLeagues.push.apply(allLeagues, sport.leagues);
  });
  return allLeagues;
};

Next, you can use this function in your view by binding to it:

<div ng-repeat="league in flattenLeagues() | filter:query">
  {{league.name}}
</div>

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 data segments in Knockoutjs using various models

I'm trying to figure out why Knockout.js won't allow me to access specific parts of the model data. Could it be because I am binding the model to the div that contains all the submodels (such as the Form in this example), or am I approaching this ...

Organizing data in a database the arrangement way

I'm looking to populate an array with values for "name" and "nickname" extracted from an SQLITE database and then display them in an alert box. This task is part of a JavaScript project developed using Titanium Appcelerator. Below is the code snippe ...

Tips for customizing the appearance of Ionic's navigation bar

I attempted to customize the background-color of an ion-nav-bar by using the following code: <ion-nav-bar class="backarrow-bar" ng-style="{'background-color': rgba(255, 0, 0, 0.5)}" style="background-color:rgba(255, 0, 0, 0.5)"> <io ...

Extract the element when the mouse is clicked

I'm currently working on developing a Chrome extension with a specific goal in mind: My aim is to capture the username when a user Ctrl-clicks on a username while browsing Reddit, and then transfer that username from the content script page to the ba ...

Determine the amount of unused vertical space within a block of text

Having applied CSS to a span element: font-height = 120px; height = 120px; line-height = 120px; The text inside the span does not completely fill the height of 120px. Is there a method to determine the offset of the text from the top and bottom boundar ...

Using AngularJS $resource to access JSON data with a root node

As a newcomer to AngularJS, I'm figuring out how to handle server responses from $resource that have a root node. Currently, my approach involves using $resource to retrieve a User object from the backend, similar to this: var User = $resource(&apos ...

Issue with Wicket: unable to generate sound for resource paths

I am having some trouble with a path in my wicket project. There is a sounds folder located within the Web Pages directory. Within my JavaScript code, I am using the following path to play sounds: audioElement.setAttribute('src', 'sounds/s ...

What sets apart a React component from a function-as-component in React?

React is really confusing to me right now. Take this simple react component for example: export default function Foo(){ return( <div> <div>some text</div> </div> ) } I want to add a child compone ...

Disable link 2 when link 1 is clicked

Looking to create a feedback form with two exclusive links. Want to ensure that if someone clicks the first link, they cannot click the second link and vice versa. Interested in exploring options like using cookies to prevent multiple clicks or possibly ...

Storing data with NPM global packages: Best practices

I have developed a global npm package that functions as a CLI tool. https://i.sstatic.net/PdT3Z.png My goal is to customize the user experience by having the package remember the user's previous choices. For example, if the user selects 'Iphone ...

How can one achieve the equivalent of Flask Safe when making an ajax call?

Having trouble replicating equivalent functions in my Ajax call as I can in regular Javascript on my main HTML page. Using Python/Flask at the back-end. Any similar methods to use the {{ variable | safe }} syntax in AJAX for similar results? My code snipp ...

Concealing a field when the PHP post is devoid of content

On page1.php, there is a form that, upon submission, redirects to page2.php where the selected information is summarized. The code snippet below on page2.php retrieves this information. I am attempting to dynamically hide certain rows if the PHP post is e ...

The regular expression pattern ((xn--)?[a-z0-9]+(-[a-z0-9]+)*.)+[a-z]{2,} is functional when used on regexpal.com, however, it does not yield the

Within the code snippet below, the regular expression in the "pattern" variable is specifically designed to only match the criteria mentioned in the comment (which requires a minimum of 1 letter followed by a dot, and then two letters). var link = "Help" ...

Is there a way to incorporate the ::after or ::before pseudo-elements into an image tag?

While working on my project, I attempted to incorporate the ::after tag (I had used ::before as well) for an image within an img tag. However, I am facing difficulties as it doesn't seem to be working. Any advice or guidance would be greatly appreciat ...

The login controller fails to retrieve any values upon submission

My current controller setup looks like this: var myApp = angular.module('myApp', ['ui.router']); myApp.controller('loginController',['$http', function($http) { this.loginForm = function(){ console.log(th ...

Is there a way to transform a dynamically created JavaScript table into JSON or XML format and then store it as a file?

A dynamic table of properties is created in JavaScript using a function: // update table PropertyWindow.prototype._update = function (text) { if (text === void 0) { text = "&lt;no properties to display&gt;"; } this._propertyWindow.html(text); ...

Utilize Selenium to extract information from a webpage, including content that is dynamically generated through JavaScript

Currently, I am facing a dilemma: my desire is to extract information from a webpage (for example, this one) regarding the apps that are available, and then store this data into a database. In my quest to achieve this task, I have opted to use crawler4j t ...

Determine whether a variable includes an alphabetic character

I need to eliminate any results from an array that include alphabetic characters. To do this, I am using the following code: if(gtin.toString().length != 13 || /[a-z\-]+/ig.test(gtin) == true) { gtin = "null"; } Although it works for some variab ...

Adding elements in an array depending on the values in a separate array

I am currently working on a task that involves summing values in an array of objects based on the Ids present in another array within the same object. Let's assume I have the following queryArray: const queryArray = [ "1" , "2" ] ...

What is the best way to create a deep clone of an XMLDocument Object using Javascript?

I am currently working on a project that involves parsing an XML file into an XMLDocument object using the browser's implementation of an XML parser, like this: new DOMParser().parseFromString(text,"text/xml"); However, I have encountered a situatio ...