Home > database >  Transform datastructure with TypeScript
Transform datastructure with TypeScript

Time:07-12

I would like to normalize and transform my data with TypeScript. The data that I get looks like this:

packages = {
  ungroupped: [
    {
      id: '0',
      status: 'active',
      owner: 'Stan Smith'
    },
    {
      id: '1',
      status: 'active',
      owner: 'Jill Smith'
    }
  ],
  groupped: [
    {
      name: 'Group 1',
      id: 1,
      accounts: [
        {
          id: '3',
          status: 'inactive',
          owner: 'Jane Smith'
        },
        {
          id: '4',
          status: 'hidden',
          owner: 'Stan Smith'
        }]
    }
   ]
};

What I would like to achieve, is this structure:

packages = [
  {
   name: null,
   id: null,
   accounts: [
     {
      id: '0',
      status: 'active',
      owner: 'Stan Smith'
     },
     {
      id: '1',
      status: 'active',
      owner: 'Jill Smith'
     }]
  },
  {
   name: 'Group XZY',
   id: 1,
   accounts: [
     {
      id: '3',
      status: 'inactive',
      owner: 'Jane Smith'
     },
     {
      id: '4',
      status: 'hidden',
      owner: 'Stan Smith'
     }]
  }
];

This is the code that I used to transform my data, but the result is not exactly what I want to have:

interface AccountGroupsUI {
   id: string;
   name: string;
   accounts: AccountUI[];
}

groups: AccountGroupsUI;

ngOnChanges(changes: SimpleChanges) {
  this.groups = [...this.packages.groupped];
  this.packages.ungroupped.map(data => {
    let newPackage = {
      id: null,
      name: null,
      accounts: this.packages.ungroupped
    };
    this.packages.push(newPackage);
  }
}

Now the code creates 2 "ungroupped" objects with the same content. I would like just one object with id: null, name: null, and all ungroupped account pushed into the accounts, but I cannot figure out how to do that. Can someone please help me?

CodePudding user response:

This looks like what you're after:

const packages = {
  ungroupped: [{
    id: '0',
    status: 'active',
    owner: 'Stan Smith'
  }, {
    id: '1',
    status: 'active',
    owner: 'Jill Smith'
  }],
  groupped: [{
    name: 'Group 1',
    id: 1,
    accounts: [{
      id: '3',
      status: 'inactive',
      owner: 'Jane Smith'
    }, {
      id: '4',
      status: 'hidden',
      owner: 'Stan Smith'
    }]
  }]
};

const result = [{
    id: null,
    name: null,
    accounts: packages.ungroupped
  },
  ...packages.groupped
];

console.log(result);


Note that groupped and ungroupped are conventionally spelled grouped and ungrouped.

  • Related