Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract keys from JSON where its value is true

Tags:

json

html

angular

I have below JSON, from this I want to extract Skills where it is true.

[  
   {  
      "_id":"5de9f351baca28556c6a4b71",
      "Name":"Harsha",
      "Age":20,
      "Gender":"M",
      "Skills":{  
         "Java":"",
         "Mule":true,
         "Angular":""
      }
   },
   {  
      "_id":"5de9f358baca28556c6a4b72",
      "Name":"Anji",
      "Age":21,
      "Gender":"M",
      "Skills":{  
         "Java":"",
         "Mule":true,
         "Angular":true
      }
   },
   {  
      "_id":"5dea110297c2b65298b136e4",
      "Name":"Abhi",
      "Age":25,
      "Gender":"M",
      "Skills":{  
         "Java":"",
         "Mule":true,
         "Angular":""
      }
   }
]

I am able to print rest of the data using below code

<table *ngIf="formTemplate">
        <tr>
            <th *ngFor="let header of questionTitleArray" >{{header}}</th>
        </tr>

        <tr *ngFor="let data of surveyDataFromDB">
                <ng-container *ngFor="let head of questionTitleArray">
                <td>{{data[head]}}</td>         
        </ng-container>
        </tr>
    </table>

(Here JSON is "surveyDataFromDB")

Below is the output I am getting

Name    Age Gender  Skills
Harsha  20  M   [object Object]
Anji    21  M   [object Object]
Abhi    25  M   [object Object]

I want Skills which are true in place of [object Object]. Please help.

like image 811
Abhi Avatar asked Dec 06 '19 09:12

Abhi


1 Answers

You can first map your object to only have the truthy ones. You can use lodash pickBy.

mappedSurveyDataFromDB = this.surveyDataFromDB.map(
    entry => ({...entry, Skills: _pickBy(entry.Skills, Boolean)}),
  );

After change the template like this:

<table>
  <tr>
    <th *ngFor="let header of questionTitleArray">{{ header }}</th>
  </tr>

  <tr *ngFor="let data of mappedSurveyDataFromDB">
    <ng-container *ngFor="let head of questionTitleArray">
      <td *ngIf="head !== 'Skills'">{{ data[head] }}</td>
      <td *ngIf="head === 'Skills'">
        <ng-container *ngFor="let entry of (data[head] | keyvalue); let last = last">
          {{ entry.key }}
          <ng-container *ngIf="!last">, </ng-container>
        </ng-container>
      </td>       
    </ng-container>
  </tr>
</table>

Stackblitz: https://stackblitz.com/edit/angular-ga7lqg

like image 162
MoxxiManagarm Avatar answered Sep 27 '22 23:09

MoxxiManagarm