What is the most efficient method for creating a new object based on the keys of the current object? Each key in the original object should correspond to a specific element in the new object - for example, activityName1
should match the first element's name
in the nested activities
array, and so on.
const obj = {
activityName1: "Bingo",
activityName2: "Bazinga",
activityType1: "Dog",
activityType2: "Term",
description: "Games are fun.",
name: "Patty"
};
Desired result:
const newObj = {
activities: [
{name: "Bingo", type: "Dog"},
{name: "Bazinga", type: "Term"}
],
description: "Games are fun.",
name: "Patty"
};
I initially considered using reduce
and Object.assign
, but I only ended up with a single key/value pair:
Object.keys(variables).reduce((obj, key) => {
if (key.includes('activity')) {
return Object.assign(obj, {
[key[key.length - 1]]: { activities: { [key]: variables[key] } } });
}
return obj;
}, {});
This resulted in an activities
array like:
[
1: {activities: {type: "Dog"},
2: {activities: {type: "Term"}
]