Home > Back-end >  Compare 2 arrays of objects by 2 different keys. And make one nested object which contains parent an
Compare 2 arrays of objects by 2 different keys. And make one nested object which contains parent an

Time:09-01

I have problem with comparing 2 arrays of objects. I was searching lodash documentation, but I was not able to find proper method. The thing is that I need to compare objects by different keys.

private parentArray: {}[] = [
    { Id: 1, Name: 'A' },
    { Id: 2, Name: 'B' },
    { Id: 3, Name: 'C' },
    { Id: 4, Name: 'D' }
  ];

private childArray: {}[] = [
    { Id: 2, parentId: 2, Name: 'a' },
    { Id: 3, parentId: 2, Name: 'b' },
    { Id: 4, parentId: 4, Name: 'c' },
    { Id: 5, parentId: 4, Name: 'd' }
  ];

I need to make a new array of nested objects where 'parentId' will be matched with 'Id' of parent which will look like that:

private newArray = [
    { Id: 1, Name: 'A', Children: [] },
    {
      Id: 2,
      Name: 'B',
      Children: [
        { Id: 2, parentId: 2, Name: 'a' },
        { Id: 3, parentId: 2, Name: 'b' }
      ]
    },
    {
      Id: 3,
      Name: 'C',
      Children: []
    },
    {
      Id: 4,
      Name: 'D',
      Children: [
        { Id: 4, parentId: 4, Name: 'c' },
        { Id: 5, parentId: 4, Name: 'd' }
      ]
    }
  ];

I was using '.intersectionWith([arrays], [comparator])' and '.isMatchWith(object, source, [customizer])' but it did not give me what I need. I will be grateful for any help.

CodePudding user response:

type Parent = {
    Id: number,
    Name: string,
}

type Child = Parent & {
    parentId: number;
}

type ParentAndChildren = ({
    Children: Child[]
} & Parent)[]


const parents: Parent[] = [
    { Id: 1, Name: 'A' },
    { Id: 2, Name: 'B' },
    { Id: 3, Name: 'C' },
    { Id: 4, Name: 'D' }
  ];

const children: Child[] = [
    { Id: 2, parentId: 2, Name: 'a' },
    { Id: 3, parentId: 2, Name: 'b' },
    { Id: 4, parentId: 4, Name: 'c' },
    { Id: 5, parentId: 4, Name: 'd' }
  ];

const output = parents.map((p: Parent) => {
    return {
        Id: p.Id,
        Name: p.Name,
        Children: children.filter((c) => p.Id === c.parentId),
    }
})

console.log(output);

CodePudding user response:

The simplest way to do this is probably

const newArray = parentArray.map(
    p => ({ ...p, Children: childArray.filter(c => c.parentId === p.Id) })
)

which results in the output you are looking for. Note that this is not necessarily the best performing algorithm in the case where parentArray and childArray are large, since we are looping over the entire childArray for every element in parentArray (so if childArray is length

  • Related