Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select from nested json array

I have a JSON I get from API as :

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

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

    }];

I want to group by primary and selectable values are Array sub

like:

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

I am able to group by primary key but I cannot get inner values. Here's what I 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>

(here is my fiddle: http://jsfiddle.net/jm6of9bu/648/)

like image 554
Shankar Regmi Avatar asked Dec 18 '25 08:12

Shankar Regmi


1 Answers

You need to flatten your array. Even with group by, ng-options works on a flat array:

$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"},
    ];

Then you could do:

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

</select>

The model will be set to the value object - e.g. {primary: "white", sub: "white2"}. If you want to set it to "white2", "black3", etc... then use:

ng-options="value.sub as value.sub group by value.primary for value in data2"
like image 76
New Dev Avatar answered Dec 20 '25 02:12

New Dev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!