Arter
Arter

Reputation: 2324

Find in json and set in another json

I have JSON 1 with this data

{position: 1, weight: 1.0079, symbol: 'H'},
{position: 2, weight: 4.0026, symbol: 'He'}

And I have another JSON 2 with this data

{position: 1, name: 'Hydrogen'},
{position: 2, name: 'Helium'}

I show this data in the angular-material table

POSITION   |   WEIGHT   |   SYMBOL
1          |   1.0079   |   H
2          |   4.0026   |   He

I need to search in the second JSON elements with position number 1 or 2 etc..., and set name instead of number, and get first JSON table like this

POSITION   |   WEIGHT   |   SYMBOL
Hydrogen   |   1.0079   |   H
Helium     |   4.0026   |   He

Is there any direct way to do this instead of push all data to new JSON?

I try, because I use ngrx@store, to make selector and get data directly to the table in HTML but i get infinity loop

export const selectElements = createSelector(
  selectElements , 
  element => (position: string) => element [position]
);

this.elements= this.store.pipe(
  select(elements.selectElements )
);

and in material table

{{ (elements | async)(elements.position) }} 

and get error in VScode

Call target is not callable

I also try to use .find() but the same error, infinity loop...

Here is stackblitz

Upvotes: 0

Views: 79

Answers (2)

Prasad Shigwan
Prasad Shigwan

Reputation: 552

Please use filter as below:

@Pipe({
  name: 'FilterData'
})
export class OrdinalPipe implements PipeTransform {

  transform(value: Element): string {
    var data =   ElementTitle.filter(
          ElementTitle => ElementTitle.position === value);
          return  data[0].name; 
  }
}

HTML code:

    <ng-container matColumnDef="position">
          <mat-header-cell *matHeaderCellDef> No. </mat-header-cell>
          <mat-cell *matCellDef="let element"> {{element.position |FilterData }} </mat-cell>
   </ng-container>

Here is the URL with filter feature. https://stackblitz.com/edit/angular-ttg6ux-sokueh?file=src/app/table-filtering-example.ts

Upvotes: 1

norbitrial
norbitrial

Reputation: 15166

I think you can use reduce() and find() combination to resolve your issue.

As Array.prototype.reduce() documentation states:

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

const arr1 = [
  {position: 1, weight: 1.0079, symbol: 'H'},
  {position: 2, weight: 4.0026, symbol: 'He'}
], arr2 = [
  {position: 1, name: 'Hydrogen'},
  {position: 2, name: 'Helium'}
];

const result = arr2.reduce((a, c) => {
  const elem = arr1.find(e => e.position === c.position);
  
  a.push({
    name: c.name,
    weight: elem.weight,
    symbol: elem.symbol
  })
  return a;
}, []);

console.log(result);

I hope that helps!

Upvotes: 1

Related Questions