Home > OS >  How can I create new object(array) by exiting object?
How can I create new object(array) by exiting object?

Time:11-24

I have object as following :

0 : {rYear: '1Y', rType: 'TypeA', rVal: 41}
1 : {rYear: '2Y', rType: 'TypeA', rVal: 11}
2 : {rYear: '3Y', rType: 'TypeA', rVal: 32}
3 : {rYear: '1Y', rType: 'TypeB', rVal: 12}
4 : {rYear: '2Y', rType: 'TypeB', rVal: 21}
5 : {rYear: '3Y', rType: 'TypeB', rVal: 16}

I want to transfer the object as below format :

0 : {rType: 'TypeA', 1Y: 41, 2Y: 11, 3Y: 32}
1 : {rType: 'TypeB', 1Y: 12, 2Y: 21, 3Y: 16}

I’ve tried to use .groupBy(collection, [iteratee=.identity]) from lodash, but dose not get what I need to achieve.

CodePudding user response:

You could use a simple reduce to group the objects based on rType:

const input = [
  { rYear: '1Y', rType: 'TypeA', rVal: 41 },
  { rYear: '2Y', rType: 'TypeA', rVal: 11 },
  { rYear: '3Y', rType: 'TypeA', rVal: 32 },
  { rYear: '1Y', rType: 'TypeB', rVal: 12 },
  { rYear: '2Y', rType: 'TypeB', rVal: 21 },
  { rYear: '3Y', rType: 'TypeB', rVal: 16 },
]

const grouped = input.reduce((acc, {  rYear, rType, rVal }) => {
    acc[rType] ??= { rType };
    acc[rType][rYear] = rVal
    return acc
  }, {})
  
const output = Object.values(grouped)

console.log(output)

CodePudding user response:

We can do it just by using Array.reduce()

let data = [ 
 {rYear: '1Y', rType: 'TypeA', rVal: 41},
 {rYear: '2Y', rType: 'TypeA', rVal: 11},
 {rYear: '3Y', rType: 'TypeA', rVal: 32},
 {rYear: '1Y', rType: 'TypeB', rVal: 12},
 {rYear: '2Y', rType: 'TypeB', rVal: 21},
 {rYear: '3Y', rType: 'TypeB', rVal: 16}
]

let result = data.reduce((a,v) =>{
  let obj = a.find(i => i.rType === v.rType)
  if(obj){
    obj[v.rYear] = v.rVal
   }else{
    obj = {'rType':v.rType}
    obj[v.rYear] = v.rVal
    a.push(obj)
   }
  return a
},[])
console.log(result)

CodePudding user response:

when I got a logic like this, I usually use a map to solve the problem. Like the following code.

const arr = [
        { rYear: "1Y", rType: "TypeA", rVal: 41 },
        { rYear: "2Y", rType: "TypeA", rVal: 11 },
        { rYear: "3Y", rType: "TypeA", rVal: 32 },
        { rYear: "1Y", rType: "TypeB", rVal: 12 },
        { rYear: "2Y", rType: "TypeB", rVal: 21 },
        { rYear: "3Y", rType: "TypeB", rVal: 16 },
      ];
      const objMap = new Map();
      arr.forEach((e) => {
        const obj = {};
        obj[e.rYear] = e.rVal;
        obj["rType"] = e.rType;
        if (objMap.get(e.rType) === undefined) {
          objMap.set(e.rType, obj);
        }
        objMap.get(e.rType)[e.rYear] = e.rVal;
      });
      const resultArr = [];
      objMap.forEach((e) => {
        resultArr.push(e);
      });

  • Related