The short answer
No, you cant.
JavaScript destructuring only allows you to override root level keys of an object, which replaces their value.
(You also usually wouldn't do this, to keep cognitive complexity low.)
The long answer
There are actually better ways to do this.
Usually when creating a new object by spreading becomes more complex, you'd simply create a function for each level of nesting, and give it a better name than I did, that correlates to your domain.
This is exactly what functions are made for; to split pieces of code to reduce complexity.
Simple example
function createDataEntry(key, data) {
return { key, data }
}
function createRecord(key, data) {
return {
key,
dataObject: {
data,
},
dataArray: [
createDataEntry(key, data),
// or simply:
// { key, data },
]
}
}
let data = [];
data.push(createRecord(1, 'foo'));
data.push(createRecord(2, 'bar'));
console.log(JSON.stringify(data, null, 2));
produces
[
{
"key": 1,
"dataObject": {
"data": "foo"
},
"dataArray": [
{
"key": 1,
"data": "foo"
}
]
},
{
"key": 2,
"dataObject": {
"data": "bar"
},
"dataArray": [
{
"key": 2,
"data": "bar"
}
]
}
]
Add + Edit example
If you want to add or edit an entry from that data array, you'll have to do a check to see if an entry already exists.
If it already exists, update it using map.
If it does not exist, use array.push().
function addOrUpdateEntry(myObject, key, data) {
let updated = false;
const updatedObject = {
...myObject,
items: myObject.items.map(member => {
if (member.key === key) {
updated = true;
return { ...member, data };
}
return member;
})
};
if (!updated) {
updatedObject.items.push({ key, data });
}
return updatedObject;
}
let data = {
items: []
};
data = addOrUpdateEntry(data, 1, "foo");
data = addOrUpdateEntry(data, 2, "bar");
data = addOrUpdateEntry(data, 2, "baz");
console.log(JSON.stringify(data, null, 2));
Which will output
{
"items": [
{
"key": 1,
"data": "foo"
},
{
"key": 2,
"data": "baz"
}
]
}
Note that mutating an existing object can easily make for undesired behaviour in JavaScript, hence the creation of a new object and returning that from the function.
This concept is called immutability.