Home » vue » Using .map to loop array of objects and store new array in object value

Using .map to loop array of objects and store new array in object value

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m currently getting data from a database of an array of objects. I need these objects to be reformatted to work with a UI package that we’re using that requires these objects to look a specific way. The main array should look like this:

[{
   trim: 123,
   id: 123,
   children: [{
      trim: 123,
      id: 123,
   }],
}]

I’m successfully looping through the main array data and reformatting it into a new array using .map; however, I’m having issues doing the same thing but for the children key that’s found in each object of the main array. Wondering if anyone could help me figure out the proper way to do this. I’ll add my current code below and will be able to clarify more if needed.

if (this.$store.state.models.models) { // this is checking for the main array coming from the database
   const reformattedModels = this.$store.state.models.models.map((model) => {
   const tableModel = {
     trim: model.name,
     id: model.id,
     children: // Need to loop here to reformat array of objects that goes for the children key,
   };
   return tableModel;
 });
 return reformattedModels;

}

The array that I need to loop through for the children key is one of the keys found in the main array from the backend. It’s called "trims" and looks like this:

[{
   name: 123,
   id: 123,
}]
Answers:

Create a reference to the function and call it recursively:

if (this.$store.state.models.models) {
  // store the function
  const mapper = model => ({
    trim: model.name,
    id: model.id,
    // use it for children, if there are any
    children: model.children?.map(mapper)
  });

  // use it for the models
  return this.$store.state.models.models.map(mapper);
}

I’m using optional chaining (?.) to call .map() only if model.children != undefined