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 into 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.
Solution:
I ended up going with Robin's solution of using a spread operator.
table = {
general: table.general,
plans: section.section.plans,
...table
};
Doing it this way meant that I had to manually create the new object because I would have to know in advance the name of the object keys and where to insert the second object.
The ideal solution would be to hand the second object to a function and let the function determine how to construct the new object without knowing in advance what the names of the keys would be and where to insert the second object. The function would have to use the key after in the second object to determine where to perform the insert; perhaps via the use of a spread operator.