Reputation: 2376
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
Reputation: 5853
Object.entries
Reduce over
the entries generated in step 1split by
delimiter '-'
the object
will act as a lookup storeextract the values
of the lookup.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