Tips for choosing data from a nested JSON array

I receive JSON data from an API in the following format:

 $scope.data = [{
        "primary": "white",
        "sub": ["white 1", "white 2", "white 3"]

    },{
        "primary": "black",
       "sub": ["black 1", "black 2", "black 3"]

    }];

My goal is to group by the primary key and have the selectable values be the sub arrays.

For example:

**White**
   white 1
   white 2
   white 3
**Black**
   Black 1
   Black 2
   Black 3

I have successfully grouped by the primary key, but I am struggling to display the inner values. Here's what I currently have:

<div ng-controller="myCtrl">
    <select
        ng-model="myOption"
        ng-options="val.primary group by value.primary for value in data">

    </select>
    <div>
        ng-model value: {{myOption}}
    </div>
</div>

(You can also view my code on this fiddle: http://jsfiddle.net/jm6of9bu/648/)

Answer №1

It is important to ensure your array is flattened before using ng-options. This directive works best with a flat array structure even when utilizing group by:

$scope.data2 = [
    {primary: "white", sub: "white1"},
    {primary: "white", sub: "white2"},
    {primary: "white", sub: "white3"},
    {primary: "black", sub: "black1"},
    {primary: "black", sub: "black2"},
    {primary: "black", sub: "black3"},
    ];

You can then implement the following code:

<select
    ng-model="myOption"
    ng-options="value as value.sub group by value.primary for value in data2">

</select>

The model will contain the entire value object, such as

{primary: "white", sub: "white2"}
. If you prefer it to hold just "white2", "black3", etc., you should use:

ng-options="value.sub as value.sub group by value.primary for value in data2"

Answer №2

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) { 

$scope.data = [{
        "main": "red",
        "subvalues": ["red 1", "red 2", "red 3"]

    },{
        "main": "blue",
       "subvalues": ["blue 1", "blue 2", "blue 3"]

    }];


$scope.selectedData=[];
$scope.data.forEach(function(item,index){
    item.subvalues.forEach(function(value,index){    
    $scope.selectedData.push({
      'type':item.main,
      'info':value
      });
    });    
});
  
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp' ng-controller="myCtrl">
    <select
        ng-model="chosenOption"
        ng-options="data.info as data.info group by data.type for data in selectedData">

    </select>
    <div>
        Selected value: {{chosenOption}}
    </div>
</div>

Answer №3

After some experimenting, I was able to find a solution with just a small adjustment:

This is what I attempted:

<div ng-controller="myCtrl">
<select ng-model="myOption" ng-options="value.sub group by value.primary for value in data2">

I also restructured my nested JSON like this:

function myCtrl($scope) {
   datas = [{
        "primary": "white",
        "sub": ["white 1", "white 2", "white 3"]

    },{
        "primary": "black",
       "sub": ["black 1", "black 2", "black 3"]
    }];
   $scope.data2 = [];
   datas.forEach(function(entry){
     entry.sub.forEach(function(sub){
        $scope.data2.push({primary:entry.primary,sub:sub})
    });
 });
};

You can view the fiddle here: http://jsfiddle.net/jm6of9bu/658/

Answer №4

It seems like there might be some confusion about what you're looking for, but

If you'd like the sub values to be displayed instead, try changing val.primary to val.sub before grouping

<div ng-controller="myCtrl">
    <select
        ng-model="myOption"
          ng-options="val.sub group by value.primary for value in datas">

    </select>
    <div>
       Selected value: {{myOption}}
    </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

What is preventing me from accessing these attributes using "${array[a].name}"?

What is preventing me from reading the properties using ${ array[a].name } with For Of loop? I created an example with an array of objects to help diagnose the problem. const movies = [{ title: "Shrek", year: 2001 }, { title: "Shrek 2", ...

I am facing a challenge with AngularJS where I am unable to navigate between pages using the

I'm having issues with my route file app.js. Whenever I click on any link or button, it redirects me to books.html. What could be the mistake I'm making? var myApp = angular.module('myApp', ['ngRoute']); myApp.config([&apo ...

obtaining user information from API using the x-api-key

As a beginner JavaScript programmer, I'm attempting to fetch user information. Is there a simple way to search for a specific person like Laurel Gates with the USERID: 987654321? English is not my native language, so I apologize for any mistakes. Here ...

Initiating parameterized Jenkins build utilizing Jersey REST with JSON parameters

Looking for guidance on how to initiate a Jenkins parameterized build through Jersey REST API, where the parameter values are provided in JSON format. Any tips or examples would be greatly appreciated. ...

There was an issue encountered while attempting to add concurrently to the package.json

Bundle of scripts in package.json "scripts": { "begin": "node back-end/server.js", "serve": "nodemon back-end/server.js", "client-initiate": "npm start --prefix front-end", ...

Validating Arrays of Input Elements using JQuery

I have a task to validate an array of input text elements (mileage). Here is an example of what I need to accomplish: <tbody> <c:forEach items="${list}" var="item"> <tr> <!--some other columns---> ...

What is the method in JavaScript to display the information stored in a title attribute?

Can anyone help me with this code snippet I have? <i class="my-class" title="AB"> ::before </i> I need to extract and output the value of the title attribute, which is AB Example output should be: <span class="my-class">AB</spa ...

I'm having trouble extracting image bytes from my JSON array, could someone lend me a hand?

I am struggling to extract the ItemImage1 and Bytes from my JSON Array. Can anyone assist me with this? {"FetchAllItemsResult":[{"ItemID":5, "ItemCategoryID":225, "ItemCode":"1263", "barcode":"0010000005", "ItemDescription":"CAKE TRAY ROUND TEFAL 1 PCS ...

Unable to delete product from shopping cart within React Redux reducer

Currently, I am tackling the challenge of fixing a bug in the shopping cart feature of an e-commerce website I'm working on. The issue lies with the remove functionality not functioning as expected. Within the state, there are cartItems that can be ad ...

Error displaying cookies when loading in browser

Currently, I am working on building a webpage using node.js with the hbs engine and express framework. After a user logs in, I am trying to capture cookies and use them for authentication purposes on a specific page. app.get('/path', function (r ...

Submitting a Complex JSON Object through a URL with Javascript

I am attempting to send a complex JSON Object in a URL input = { "id": 1, "sd": "123", "filter": { "h": 1,"road": true }, "legs": [{ "id": 1, "x1": -0.001, "y1": 51.122 }, { "id": 2, "x1": -12, "y1": 12 }] }; I have experimented with these methods data ...

Angular UI.Router's $state templates use $rootScope for ng-models

I'm encountering a strange issue where the ui-view template in my $state controller seems to be interacting with $rootScope instead of $scope. However, it does initialize $scope variables properly. For instance: if I have $scope.name = "test" and i ...

What steps should I take to generate a 2-Dimension Input Array from scratch?

I am working on a project that involves creating a 2-Dimensional array of text-based numerical inputs. I aim to use the standard HTML input type box for this purpose: <input type="text"> The number of rows and columns in the array will depend o ...

What is the best way to merge two JSON objects linked by a foreign key in Angular?

Looking to display data from two JSON objects in a table, connected by a foreign key. The first set of JSON data is as follows: $scope.items = [ {status_id: 1, type: 1}, {status_id: 2, type: 2}, {status_id: 1, type: 3}, {status_id: 1, typ ...

Tips for preventing a React component from scrolling beyond the top of the page

I am looking to achieve a specific behavior with one of my react components when a user scrolls down a page. I want the component to reach the top of the page and stay there without moving any further up. Here is an Imgur link to the 'intranet' ...

Building a Nested JSON Structure with Python Pandas

I'm struggling with adjusting my code to incorporate an additional dictionary for separating "hostNumber" and "hostMode" in the final output. I came across this code on Stack Overflow and attempted to modify it: import json from json import dumps to ...

Is it true that Javascript does not allow for saving or outputting actions?

After coming across this question, I discovered a way to extract a specific element from a Google translate page using Javascript. However, I also learned that it is nearly impossible to directly save something to the clipboard in Javascript without user i ...

Learn how to implement RSS into your Next.js MDX Blog by integrating the `rss` module for Node JS. Discover the process of converting MDX content to HTML effortlessly

Having trouble converting MDX to HTML at the moment. This task is for Tailwind Blog You can find the complete code on Github here → https://github.com/tailwindlabs/blog.tailwindcss.com Below is the relevant code snippet: scripts/build-rss.js import fs ...

Guide on integrating AngularJS routes with Express (Node.js) to handle requests for a new page

When using Express to load AngularJS from a static directory, my usual request is http://localhost/. Express serves me the index.html file along with all the necessary Angular files. In my Angular app, I have configured routes that replace content in an ng ...

Retrieving data from JSON column is taking an unusually long time

Currently, I am working with a CSV file that contains a large amount of data. Within this file, there is a column named ExtraParams which holds JSON objects. My goal is to extract a specific value using a key, but the process is taking longer than expected ...