Create a list of objects without an array

Advertisements

I need to get data in this format:

{
    name: 'template',
    type: index
},
{
    name: 'template',
    type: index 
},
setTemplateList(), 
{
    name: 'template',
    type: index
},…

They should not be in an array, because I return them as is to another file containing objects.

Here’s what I’m trying to do:

export function setTemplateList() {
      const templateList = [
  {title: 'About', value: 'aboutTemplate'},
  {title: 'Contact', value: 'contactTemplate'}
]
    
      let object = {};
    
      templateList.forEach(function (index, value) {
        let obj = {
          name: 'template',
          type: value.value
        }
    
        // I want to push into object here
      });
    
      return object;
    }

How can I do it? Thank you

>Solution :

It sounds to me like what you’re trying to do is inject elements into an array without those elements themselves being an array. So, for example, imagine this array structure:

[
  {
    name: 'template',
    type: index
  },
  {
    name: 'template',
    type: index 
  }
]

If I’m understanding you correctly, you want to be able to invoke a function in the middle of this structure:

[
  {
    name: 'template',
    type: index
  },
  {
    name: 'template',
    type: index 
  },
  someFunction()
]

And that function should return more then one element to be added to this overall array, resulting in:

[
  {
    name: 'template',
    type: index
  },
  {
    name: 'template',
    type: index 
  },
  {
    name: 'template',
    type: index
  },
  {
    name: 'template',
    type: index 
  }
]

But you don’t want that function to return an array, because that would result in:

[
  {
    name: 'template',
    type: index
  },
  {
    name: 'template',
    type: index 
  },
  [
    {
      name: 'template',
      type: index
    },
    {
      name: 'template',
      type: index 
    }
  ]
]

Which, while structureally permitted in JavaScript, is not the structure you want.

In this case, it sounds like you already have what you want but just need to change how you use it.

The function should return an array. In fact, it has to. Because that’s how a group of objects is structured… as an array. However, you don’t have to embed the array itself into your structure. You can spread the result of the function into the overall array:

[
  {
    name: 'template',
    type: index
  },
  {
    name: 'template',
    type: index 
  },
  ...someFunction() // <-- note the spread operator here
]

What this would do is take the result of the function (an array) and add its contents to the overall structure, rather than add the result itself to the overall structure. Which would result in one overall consistent array structure.

Leave a ReplyCancel reply