Oleksandr Fomin
Oleksandr Fomin

Reputation: 2376

Split one object into multiple object by ID

I have an object of the following structure

const obj = {
  [name-1]: 'Peter',
  [name-2]: 'Mark',
  [name-3]: 'Rich',

  [age-1]: 25,
  [age-2]: 30,
  [age-3]: 45
}

I need to split it into 3 separate object like that

const obj1 = {
[name-1]: 'Peter',
[age-1]: 25,
 }

const obj2 = {
[name-2]: 'Mark',
[age-2]: 30,
 }

const obj3 = {
[name-3]: 'Rich',
[age-3]: 45,
 }

How can I achieve that?

Upvotes: 0

Views: 129

Answers (1)

Kunal Mukherjee
Kunal Mukherjee

Reputation: 5853

  1. Begin by getting entries of the input object using Object.entries
  2. Reduce over the entries generated in step 1
  3. For each iteration's current value split by delimiter '-'
  4. Reduce it to an object, the object will act as a lookup store
  5. Post doing that just extract the values of the lookup.
  6. Transform the individual entries back to its individual object using Object.fromEntries

const obj = {
  'name-1': 'Peter',
  'name-2': 'Mark',
  'name-3': 'Rich',

  'age-1': 25,
  'age-2': 30,
  'age-3': 45
};

const groupedResult = Object.values(Object.entries(obj).reduce((r, c) => {
    const [key, val] = c;
    const split = key.split('-');

    if (!r[split[1]]) {
      r[split[1]] = [c];
    } else {
      r[split[1]].push(c);
    }

    return r;
  }, Object.create(null)))
  .map((value) => Object.fromEntries(value));

console.log(groupedResult);

Upvotes: 1

Related Questions