I am looking to assign unique ids to an array of objects: For example:
const exercises = [
{
type: "yoga",
locations: [
{
name: 'studio',
day: 'Wednesday'
},
{
name: 'home',
day: 'Friday'
}
],
active: true
},
{
type: "swim",
locations: [
{
name: 'pool',
day: 'Tuesday'
},
{
name: 'lake',
day: 'Thursday'
}
],
active: true
}
]
In this scenario, I aim to add ids to the exercises
array and its nested locations
array.
My approach involves iterating through the arrays as shown below:
const idMappings = exercises.map((exercise) => {
const exerciseIdMapping = exercise.id ? exercise : { ...exercise, id: uuid.v4() }; // if id exists, return object as is; else generate a random id
const locationsIdMapping = exerciseIdMapping.locations.map((location) => {
return location.id ? location : { ...location, id: uuid.v4() }; // repeat process for nested array
});
return { ...exerciseIdMapping, locations: locationsIdMapping }; // return updated values with ids
});
The result includes unique ids for each location:
const exercises = [
{
id: "0000-0000-8888-9f24-f8e1f2402a9b",
type: "yoga",
locations: [
{
id: "0000-1111-7777-9f24-f8e1f2402a9b",
name: 'studio',
day: 'Wednesday'
},
{
id: "0000-2222-6666-9f24-f8e1f2402a9b",
name: 'home',
day: 'Friday'
}
],
active: true
},
{
id: "1111-0000-4444-9f24-f8e1f2402a9b",
type: "swim",
locations: [
{
id: "1111-1111-3333-9f24-f8e1f2402a9b",
name: 'pool',
day: 'Tuesday'
},
{
id: "1111-2222-2222-9f24-f8e1f2402a9b",
name: 'lake',
day: 'Thursday'
}
],
active: true
}
]
While this method achieves the desired outcome, I wonder if there is a more efficient way to tackle this issue. Are there alternative ES6 functions that could streamline this process without multiple mappings?