Home > database >  I want to format the typescript object array to create a new array
I want to format the typescript object array to create a new array

Time:03-13

I am using typescript.

I want to create a new array using the userData and GroupData arrays.

If the groupId in the userData array and the userGroupId in the GroupData array are the same, I want to put the group of the first object with type 1 in the context.
if there is no type1, I want to put null.

I want to create an array like ①.
Errors occur where push is used. (Property 'push' does not exist for type 'UserGroup'. ts(2339))

①Wanted Value
  [
    { id: 1, groupId: 10, title: 'test1', content: 'aa' },
    { id: 2, groupId: 11, title: 'test2', content: 'bb' },
    { id: 3, groupId: 12, title: 'test3', content: 'null' },
    { id: 4, groupId: 13, title: 'test4', content: 'dd' },
  ];

const userData = [
  { id: 1, groupId: 10, title: 'test1' },
  { id: 2, groupId: 11, title: 'test2' },
  { id: 3, groupId: 12, title: 'test3' },
  { id: 4, groupId: 13, title: 'test4' },
  ];

const GroupData = [
  { id: 1, userGroupId: 10, group: 'aa' type: 1},
  { id: 2, userGroupId: 11, group: 'bb',type: 1},
  { id: 3, userGroupId: 11, group: 'cc',  type: 1},
  { id: 3, userGroupId: 12, group: 'cc',  type: 2},
  { id: 4, userGroupId: 13, group: 'dd', type: 1},
  ];

  type UserType = {
    id: number;
    groupId: number;
    title: string;
  };

  type GroupType = {
    id: number;
    userId: number;
    group: string;
  };

  type UserGroup = UserType & {
    content: string;
  };

  const toBlock = () => {
    const blocks: UserGroup[] = [];
    let count = 0;
    userData.map(user => {
      GroupData.map(group => {
        if (user.groupId === group.userGroupId) {
          blocks[count].push({ ...user, content: group.group });
        }
      });
      count  ;
    });
  };

CodePudding user response:

Isn't it a fairly simple nested loops scenario. Something like this

  userData.forEach(x=>{
  let firstElem = GroupData.find(g=>g.userGroupId === x.groupId && g.type === 1);

  let content=null;
  if(firstElem)
  {
      content = firstElem.group;
  }

  resultArr.push({id: x.id, groupId: x.groupId, title: x.title, content: content});
  });

So basically we are iterating over the userData array and for each of its item, calling find (find returns the first match) on GroupData array. If the match is not found, then content element will have null, otherwise it will have the value of the group field from the array.

  • Related