Home > Software design >  How to merge objects of an array having same property and different values using typescript?
How to merge objects of an array having same property and different values using typescript?

Time:08-20

  interface IData{
  cabinTo:string[];
  cabinFrom:string;
  }

  const dataAfterIteration=
   [{cabinTo:"A",cabinFrom:"B"},
    {cabinTo:"A",cabinFrom:"C"}, 
    {cabinTo:"B",cabinFrom:"C"}, 
    {cabinTo:"C",cabinFrom:"A"}]

    let dataToPost: Array<IData>=[];

Need to push the data to dataToPost in such a way that for same cabinFrom value all the cabinTo value will be merged.

Answer should be

dataToPost =[{cabinTo:["A"],cabinFrom:"B"},{cabinTo:["A,B"],cabinFrom:"C"},{cabinTo:["C"],cabinFrom:"A"}]

CodePudding user response:

I think what you want is

const dataAfterIteration = [{
    cabinTo: "A",
    cabinFrom: "B"
  },
  {
    cabinTo: "A",
    cabinFrom: "C"
  },
  {
    cabinTo: "B",
    cabinFrom: "C"
  },
  {
    cabinTo: "C",
    cabinFrom: "A"
  }
]


let cabinFromToHash = {}
for (const data of dataAfterIteration) {
  if (!Array.isArray(cabinFromToHash[data.cabinFrom])) {
    cabinFromToHash[data.cabinFrom] = []
  }
  cabinFromToHash[data.cabinFrom].push(data.cabinTo)
}


const format = Object.keys(cabinFromToHash).map(item => {
    return { cabinFrom: item, cabinTo: cabinFromToHash[item] }
})

console.log(format)

CodePudding user response:

var dataAfterIteration = [{
    cabinTo: "A",
    cabinFrom: "B"
  },
  {
    cabinTo: "A",
    cabinFrom: "C"
  },
  {
    cabinTo: "B",
    cabinFrom: "C"
  },
  {
    cabinTo: "C",
    cabinFrom: "A"
  }
];

var groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};

var groupedItems = groupBy(dataAfterIteration, "cabinFrom");
var dataToPost = Object.keys(groupedItems).map(it => ({
  cabinFrom: it,
  cabinTo: groupedItems[it].map(r => r.cabinTo)
}));

console.log(dataToPost)

CodePudding user response:

try this

function mergeData(data: { cabinTo: string; cabinFrom: string }[]): IData[] {
    const dataToPost = new Map<string, string[]>();
    for (const { cabinTo, cabinFrom } of data) {
        if (!dataToPost.has(cabinFrom)) dataToPost.set(cabinFrom, []);
        dataToPost.get(cabinFrom)?.push(cabinTo);
    }
    return Array.from(dataToPost.entries()).map(([cabinFrom, cabinTo]) => ({ cabinTo, cabinFrom }));
}

const dataToPost = mergeData(dataAfterIteration)
  • Related