Insert an object at certain position in an object of javascript

I have a main JavaScript object and I would like to add another object to it at a specific location.

Main object

const table = {
  general: {
    title: "general",    
    fields: [
     {
      type: "Input",
      model: "name"
     },
     {
      type: "Input",
      model: "networkDeviceMake"
     },
    {
      type: "Select",
      model: "networkDeviceStatus"
    }
  ]
 },
 location: {
   title: "location",
   fields: [
   {
     type: "Select",
     model: "locationType"
   },
   {
     type: "Input",
     model: "Floor"
   },
   {
     type: "Input",
     model: "Description"
   }
  ]
 },
};

Second object

const section = {
  after: "general",
  section: {
    plans: {
      title: "plans",
      fields: [
        {
          type: "select",
          model: "planA",
        },
        {
          type: "select",
          model: "planB",
        },
        {
          type: "select",
          model: "planC",
        }
      ]
    }
  }
};

In this case, I would like to add the second object after the general key

The result should look like this

{
  general: {
    title: "general",    
    fields: [
      {
        type: "Input",
        model: "name"
      },
      {
        type: "Input",
        model: "networkDeviceMake"
      },
      {
        type: "Select",
        model: "networkDeviceStatus"
      }
    ]
  },
  plans: {
      title: "plans",
      fields: [
        {
          type: "select",
          model: "planA",
        },
        {
          type: "select",
          model: "planB",
        },
        {
          type: "select",
          model: "planC",
        }
      ]
    }
  },
  location: {
    title: "location",
    fields: [
      {
        type: "Select",
        model: "locationType"
      },
      {
        type: "Input",
        model: "Floor"
      },
      {
        type: "Input",
        model: "Description"
      }
    ]
  },
}

You will notice that in the second object I provide the key after that I want to use to determine where the second object should be added to the main object.

I understand that using main = Object.assign(main, second) will result in the second object being added at the end of the main and that is not my objective.

Cheers.

Update: The order matters in regards to how it will be implemented, and the implementation can not be changed. The second object will be handed in to a function and from there I expect we would need to iterate over the main object and then add the second object at the appropriate point.



Read more here: https://stackoverflow.com/questions/68466131/insert-an-object-at-certain-position-in-an-object-of-javascript

Content Attribution

This content was originally published by Shiers at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: