Skip to content Skip to sidebar Skip to footer

Merge Data From Different Queries Without Duplicates

I am getting data from three different queries via Api. I want data to be merged without the duplicate data. This is my function where i am merging the data: getStaffCount(data) {

Solution 1:

As an object

if the data is an object the easy way to do that is the spread opperator

const combinedData = {
  ...dataSrc1,
  ...dataSrc2,
  ...dataSrc3,
}

All matching keys will be overwritten by the previous

As an array

It's a bit more complex. Assuming your object has a unique id (or any value to identify 2 as the same item) you can use a Set since they can only have unique values.

const array = [
  ...dataSrc1,
  ...dataSrc2,
  ...dataSrc3,
]
const unique = [...newSet(array.map(item => item.id))];

Solution 2:

Your answer to my question about what the data looks like and how to group them didn't make any sense, neither did you answer Joe just showed the json data and tell him where the data comes from instead of what it is.

So I assume you group by Name and Account is ignored. You can group them in the following way:

const data = {
  results: {
    StaffCount: [
      {
        Name: 'a',
        Accounts: 2,
      },
      {
        Name: 'b',
        Accounts: 20,
      },
    ],
    RepProviderAccount: [
      {
        Name: 'a',
        Accnt: 3,
      },
    ],
    ProviderAccount: [
      {
        Name: 'a',
        Account: 1,
      },
    ],
  },
};
const grouped = [
  ...data.results.StaffCount,
  ...data.results.RepProviderAccount,
  ...data.results.ProviderAccount,
].reduce((result, item) => {
  const {
    Name,
    Account = 0,
    Accounts = 0,
    Accnt = 0,
  } = item;
  const existing = result.get(item.Name) || {
    Name,
    Account: 0,
    Accounts: 0,
    Accnt: 0,
  };
  existing.Account += Account;
  existing.Accounts += Accounts;
  existing.Accnt += Accnt;
  return result.set(Name, existing);
}, newMap());
console.log([...grouped.values()]);

In case this doesn't work for you can you please update your question and provide code as in my answer with the expected input and output? You can respond to this answer and I'll have a look at your question again.

This may actually be an xy problem, you are fetching 3 data sources and then trying to group and sum them but maybe you can just get 1 data source and try salesforce to group and sum them in the query. I don't know enough about salesforce but maybe you can ask another question tagging it with soql if it's possible to just get the data grouped and summed.

Post a Comment for "Merge Data From Different Queries Without Duplicates"