How to generate a Javascript Object Array dynamically

Asked

Viewed 181 times

-1

I want to "assemble" a JSON object array with data from the database, but some challenges have arisen.

I have the following selection field with a method that is called every time the value is changed - (change)='generateJSON()':

<form [formGroup]='productForm' class="mt-4" autocomplete="off">

    <div class="form-row">
        <div class="form-group col-md-12">
            <label for="ProductName" placement="right" ngbTooltip="Nome do produto">Product Name <small>(POF)</small></label>
            <small *ngIf="productName != null && productName?.ProductInfos != null">
                <a [href]="productName?.ProductInfos" target="_blank" rel="noopener noreferrer">- Intranet ({{ productName?.ProductName | reducedName:25 }})</a>
            </small>
            <ng-select id="ProductName" autofocus (change)="generateJSON()"
                class="isRequired ajustar"
                [items]="productNames"
                [selectOnTab]="true"
                bindLabel="ProductName"
                dropdownPosition="auto"
                labelForId="AccountOwner"
                placeholder="Search a product"
                [virtualScroll]="true"
                formControlName="ProductName">
                    <ng-template ng-option-tmp let-item="item" let-search="searchTerm">
                        <div><span [ngOptionHighlight]="search">{{ item.ProductName }}</span></div>
                    </ng-template>
            </ng-select>
        </div>
    </div>

</form>

GenerateJSON method():

public generateJSON(): void {
        this.product = this.productForm.get('ProductName').value;

        this.productHierarchyService.getDataForJSON(this.product.id)
            .subscribe(
                productHierarchy => this.productHierarchy = productHierarchy,
                err => console.log(err),
                () => this.pof_json()
            )
    }

Every time the value of the selection field is changed a query is made in the database bringing all possible settings for a product. Something like: inserir a descrição da imagem aqui

The pof_json() method has the function of creating JSON dynamically. I would like JSON to follow the following structure.

POF = [
    {
        "ID":"ID_POE",
        "POE_NAME":"POE_NAME",
        "ATTRIBUTES": [
            {
                "ID":"ID_ATTR",
                "ATTR_NAME":"ATTR_NAME",
                "VALUE": [
                    {
                        "ID":"ID_VALUE",
                        "VALUE_NAME":"VALUE_NAME"
                    }
                ]
            }
        ]
    }
]

As you can see, the POF variable is an array of javascript objects that can have one or more POE. And each POE can have one or more Attributes and finally each attribute can have one or more values.

But one of the problems is to remove the repeated information, because, as can be seen in the database image, there are 233 lines, but actually there are only 3 different POE’s and 4 different attributes.

And another challenge would be to correctly associate the values of POE, Attributes and Values. Example: POE -> AC CIRCUIT has 2 attributes and each attribute has its respective values. inserir a descrição da imagem aqui

Any suggestions on how to do this?

EDIT 1: return value for this.productHierarchy

inserir a descrição da imagem aqui

  • At ". subscribe(productHierarchy => this.productHierarchy = productHierarchy", you could put the returned value into "productHierarchy" ?

  • I added what you asked for. The return will depend on what I select in the select field

  • I wanted the data in json/txt and not the print, because in print I cannot see/manipulate the whole object. Ex: [ { POD_ID: 1, POF: "POF 1" ... }, { POD_ID: 2, POF: "POF 2" ... } , { POD_ID: 3, POF: "POF 3" ... } ].

  • https://drive.google.com/file/d/1-QZBNi7QxPoeffE_aE2SvfeKPOgQZTfM/view?usp=sharing

  • If it worked, take it as an answer.

  • Thank you so much for your help. I’m testing the code now

Show 1 more comment

1 answer

2


$.getJSON("Relacionamentos.json", function(data) {
  var POE_IDs = data
    .map(x => x.POE_ID)
    .filter((v, i, s) => s.indexOf(v) === i);

  var test = POE_IDs
    .reduce(
      (a, c) => {

        var ATTRIBUTES = data
          .filter(x => x.POE_ID == c)
          .map(x => x.ATTR_ID)
          .filter((v, i, s) => s.indexOf(v) === i);


        return a.concat({
          ID: c,
          POE_NAME: data.find(x => x.POE_ID == c).POE,
          ATTRIBUTES: ATTRIBUTES.reduce((a2, c2) => a2.concat({
            ID: c2,
            ATTR_NAME: data.find(x => x.POE_ID == c && x.ATTR_ID == c2).ATTR,
            VALUE: data.filter(x => x.POE_ID == c && x.ATTR_ID == c2).reduce((a3, c3) => a3.concat({
              ID: c3.VALUES_ID,
              VALUE: c3.VALUES
            }), [])
          }), [])
        })
      }, []);

      console.log(test);
});

Take a look here, see the return in the console.log: test

  • 1

    It worked very well Rdyego. Thanks. I didn’t understand much of what was done in the code, but I’ll try to learn. Complexity above my current knowledge. Again, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.