Ravi khatri
Ravi khatri

Reputation: 643

Group array items on basis of dynamic keys

I have an array which is something like this:

[
  { KEY1: 190 },
  { KEY1: 10 },
  { KEY2: 50 },
  { KEY2: 20 },
  { KEY3: 155 },
  { KEY3: 20511 }
]

I want to convert this into:

[
  {
    KEY1: 190,
    KEY2: 50,
    KEY3: 155 
  },
  {
    KEY1: 10,
    KEY2: 20,
    KEY3: 20511
  }
]

These keys are dynamic and can be n number of times.

Upvotes: 0

Views: 186

Answers (2)

Sean
Sean

Reputation: 8031

This would be another (more easily understandable, in my opinion) way to approach it. It creates an array of new objects, and assigns the key and value to the earliest object that doesn't yet have that key.

const oldData = [
  { KEY1: 190 },
  { KEY1: 10 },
  { KEY2: 50 },
  { KEY2: 20 },
  { KEY3: 155 },
  { KEY3: 20511 }
]

const convert = (arr) => {
  let newArr = []
  arr.forEach((obj) => {
    for (let i = 0; i < newArr.length + 1; i++) {
      newArr[i] = newArr[i] || {}
      let key = Object.keys(obj)[0]
      if (!newArr[i].hasOwnProperty(key)) { 
        newArr[i][key] = obj[key]
        break
      }
    }
  })
  return newArr
}

const newData = convert(oldData)
console.log(newData)

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386570

You could take an object for keeping track of the indices of same keys and build objects with only one same key of the given data.

const
    data = [{ TK_CEOLTIPTOTSHARESRESER: 190 }, { TK_CEOLTIPTOTSHARESRESER: 10 }, { TK_CEOSHARESOUTSTANDING: 50 }, { TK_CEOSHARESOUTSTANDING: 20 }, {  TK_EMPLOYEEOPTIONSGRANTE: 155 }, { TK_EMPLOYEEOPTIONSGRANTE: 20511 }],
    indices = {},
    result = data.reduce((r, o) => {
        const
            key = Object.keys(o)[0],
            index = indices[key] = (indices[key] ?? -1) + 1;

        Object.assign(r[index] ??= {}, o);
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Related Questions