0

I have this array that has to be filled with objects. Each object has a slug with 4 sections divided by "-" (for example: test-dx-ef-1) and depending on it I have to place them in an array at a specific index named with the slug section.

I tried looping all the inputs and directly setting the object like so:

var data = []
objects.forEach((obj) => {

    var slug = obj.slug.split('-')
    data[slug[0]][slug[1]][slug[2]][slug[3]] = obj

}

But it didn't work, as apparently, even if data[slug[0]] can be created, data[slug[0]][slug[1]] results undefined and an error is thrown.

Is there a way in which I can accomplish this?

Fabio R.
  • 393
  • 3
  • 15
  • Does this answer your question? [Javascript: how to dynamically create nested objects using object names given by an array](https://stackoverflow.com/questions/5484673/javascript-how-to-dynamically-create-nested-objects-using-object-names-given-by) - tl;dr loop through the number of slugs and create the relevant property each iteration. – D M May 24 '22 at 16:43
  • Could you add the expected outcome? – axtck May 24 '22 at 16:45

0 Answers0