How can I use JavaScript to convert a JSON object into an array for iteration with ng-repeat?

Upon retrieving my JSON object from Firebase, I am faced with the challenge of converting a list into an array for binding in HTML using ng-repeat.

The structure of my JSON object is as follows:


{
  "cats1": {
    "Name": "cricket",
    "imgUrl": "some url",
    "list1": {
      "bat": {
        "Name": "bat",
        "imgUrl": "some url",
        "price": "$100"
      },
      "pads": {
        "displayName": "pads",
        "imgUrl": "some url",
        "price": "$50"
      }
    }
  },
  "cats2": {
    "Name": "football",
    "imgUrl": "some url"
  }
}

This is the desired array structure:

I need the data structured in this way to ensure that when adding new items, they are uniquely stored under the cricket category.

[
  {
    "Name": "cricket",
    "imgUrl": "some url",
    "list1": [
      {
        "Name": "bat",
        "imgUrl": "some url",
        "price": "$100"
      },
      {
        "displayName": "pads",
        "imgUrl": "some url",
        "price": "$50"
      }
    ]
  },
  {
    "Name": "football",
    "imgUrl": "some url"
  }
]

I am relatively new to Angular and would appreciate any assistance in resolving this issue.

Answer №1

Utilize the Object.keys method and pass it to Array.prototype.map in order to generate the desired array - check out the demonstration below:

var object={cats1:{Name:"cricket",imgUrl:"some url",list1:{bat:{Name:"bat",imgUrl:"some url",price:"$100"},pads:{displayName:"pads",imgUrl:"some url",price:"$50"}}},cats2:{Name:"football",imgUrl:"some url"}};

var result = Object.keys(object).map(e=>object[e]);

console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}

EDIT:

Updated solution to convert list1 into an array:

var object={cats1:{Name:"cricket",imgUrl:"some url",list1:{bat:{Name:"bat",imgUrl:"some url",price:"$100"},pads:{displayName:"pads",imgUrl:"some url",price:"$50"}}},cats2:{Name:"football",imgUrl:"some url"}};

var result = Object.keys(object).map(function(e){
  Object.keys(object[e]).forEach(function(k){
     if(typeof object[e][k] == "object") {
       object[e][k] = Object.keys(object[e][k]).map(function(l){
         return object[e][k][l];
       });
     }
  });
  return object[e];
});

console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}

Answer №2

Recursion can be used, but be cautious as it may cause freezing for large objects and potentially result in a Maximum Call Stack exceeded error.

Logic

  • Iterate over the object and check if all entries are themselves objects.
  • If they are, a simple
    Object.keys(obj).map(x=>obj[x])
    will suffice.
  • If not, you will need to copy individual values, and if an entry is an object, iterate through it recursively. One way is to loop through each key and return the value if it is not an object.

function ObjectToArray(obj) {
  if (typeof(obj) === 'object') {
    var keys = Object.keys(obj);
    var allObjects = keys.every(x => typeof(obj[x]) === 'object');
    if (allObjects) {
      return keys.map(x => ObjectToArray(obj[x]));
    } else {
      var o = {};
      keys.forEach(x => {
        o[x] = ObjectToArray(obj[x])
      });
      return o;
    }
  } else {
    return obj;
  }
}

var d={cats1:{Name:"cricket",imgUrl:"some url",list1:{bat:{Name:"bat",imgUrl:"some url",price:"$100"},pads:{displayName:"pads",imgUrl:"some url",price:"$50"}}},cats2:{Name:"football",imgUrl:"some url"}};

console.log(ObjectToArray(d))

Answer №3

You can achieve something similar to this approach by looping through the keys of the input object and removing them.

var app = angular.module("sampleApp", []);

app.controller("sampleController", ["$scope",
  function($scope) {
    $scope.result = {
      "cats1": {
        "Name": "cricket",
        "imgUrl": "some url",
        "list1": {
          "bat": {
            "Name": "bat",
            "imgUrl": "some url",
            "price": "$100"
          },
          "pads": {
            "displayName": "pads",
            "imgUrl": "some url",
            "price": "$50"
          }
        }
      },
      "cats2": {
        "Name": "football",
        "imgUrl": "some url"
      }
    };
    $scope.format = Object.keys($scope.result).map((key) => $scope.result[key])
  }
]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div ng-app="sampleApp">
  <div ng-controller="sampleController">

    <div>Formatted</div>
    <pre>{{format | json}}</pre>
  </div>
</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

transferring data from JavaScript on the client side to Express on the server side

Using JavaScript, I have created the HTML DOM that you see in the code below. Now, my goal is to send the value of an input created in JavaScript to the server side. The server is built with node.js and express framework. Once the value is sent to the serv ...

I encountered an issue where the data I passed to a component ended up being undefined

So here's the scenario: I'm working on a Next.js project where I have a context for modals. In this context, I store modal details in an array called modalBase. Additionally, I fetch data from another context (toolsContext) to pass it to componen ...

Combining multiple AngularJS expressions to form a URL within an interpolation statement

While this explanation may be lengthy, I appreciate your patience as I try to articulate the issue at hand. The error I'm currently encountering is as follows: Error: [$interpolate:noconcat] Error while interpolating: Strict Contextual Escaping disa ...

Transferring Specific Information to Individual Fancybox Instances

I'm currently in the process of integrating Fancybox 3 into my application. My goal is to create a custom button that performs specific functions for each instance, requiring additional data such as photoId and settingsId. To illustrate: HTML: Withi ...

Tooltips for Images in Vega Charts

As a developer skilled in d3, I am navigating the world of VEGA charts and seeking guidance on how to incorporate an image in a tooltip. Do you have any suggestions for me? For example, considering this particular scenario: If we assume there is an addit ...

No information available at the moment

When the data is not present, it displays as "display none"... However, I want it to show "no data found" This is the current code if (a.innerHTML.toUpperCase().indexOf(filter) > -1) { li[i].style.display = ""; } else { li[i].styl ...

Having trouble passing parameters to the Mongo find collection operation

I'm having trouble with my code where req.params only gets a value after db.collection.find is executed. Can someone help me figure out what I'm doing wrong? exports.findAll = function(req, res) { var postal = parseInt(req.params.postal); ...

Incorporating a delay into looped HTTP requests while effectively utilizing Promise.all to track their completion

Greetings! In my current project, I am trying to introduce a 50ms delay before each subsequent HTTP request is sent to the server. Additionally, I aim to incorporate a functionality that triggers after all requests have been successfully made. To better e ...

Is there a way to conceal the loading screen until the website has completely loaded?

I've been working on my personal portfolio/website and encountered a bug that I can't seem to fix on my own. The issue is with the logo (aa) and text under it showing even after the content page has fully loaded, taking around 3 seconds to hide. ...

Overlaying images on top of text

Is there a way to overlay an image on text, like a pattern image? Similar to applying color with a hex value in CSS: color: #ffffff; Any ideas on how this can be achieved? I want to have a pattern over text. https://i.sstatic.net/JaNZU.jpg Appreciate ...

Prevent closure of Bootstrap offcanvas on backdrop click in a Blazor .NET application

Trying to implement an offcanvas window form and ensuring it stays open only when the user clicks the close button. Following client requirements, I need to call the offcanvas window via C# with IJSRuntime injection instead of directly from HTML. Operatin ...

Is there a way to deactivate all dot inputs on number type input in vue.js 2?

Here is an example of my HTML code: <div id="app"> <input type="number" v-model="quantity"/> </div> This is how my Vue component looks: new Vue({ el: '#app', data: { quantity: '' }, watch: { quanti ...

combine multiple keys into a single element with angular-translate

Within my application, I am retrieving translation keys from a single cell within a database table and dynamically displaying them on a settings page. While most entries will have just one key in the display object, there are some that contain multiple key ...

Instructions on converting Dart to JavaScript for a non-web platform

I am interested in compiling Dart to JS for a non-web target, such as fermyon/js or node How can I compile Dart to JS for a non-web target? Update: I have been informed that it is possible, and although I couldn't find specific documentation, there ...

Learn the steps for converting data from xlsx or csv files into JSON format

I am currently working on developing an application that allows users to upload xlsx or csv files from the frontend and submit them to a backend built with nodejs and express for processing. However, when I receive the data in the backend, it appears in th ...

Is there a way to retrieve the information from the v-text-field without using the v-model directive?

<div v-for="i in parseInt(questionCount)" :key="i"> <v-layout> <v-flex xs6 offset-3 mt-15" > <label for=""> Enter question number {{index}}:</label> <v-text-fi ...

Using Selenium to assign properties to JavaScript Objects

I have a JavaScript Object that needs to be set using Selenium WebDriver. var examplePlayResponse = { "prizeIndex" : 1, "mode" : "NORMAL", "id" : "abc123", "version" : "1.0", "gameCode" : "xyz789", "randomSeed" ...

Is there a way to work around coursera's keyboard input verification using JavaScript?

Is it possible to bypass Coursera's keyboard input verification using JavaScript? For example: What methods or techniques could be used to accomplish this? ...

Tips on how to include a single quote within a JSON value when making a webservice call

I am attempting to connect to a JSON ASP.NET web service using .NET. Everything goes smoothly when I send " { county : 'whatever' } ", but I encounter a 500 Internal Server Error when I try something like " { county : 'It\'s ok&ap ...

What strategies can be implemented to decrease the initial loading duration of a YouTube iframe video?

What are some techniques we can use to decrease iframe loading time? Is it possible to implement lazy loading for YouTube iframe videos? I experimented with initially hiding the iframe and displaying an image instead. However, when the user clicks, it req ...