I have this object with the following nested properties.
{
_id: {
agent_info: {
name: 'Ritu',
status: 'active',
avatar: null
}
},
avg_score: 100,
}
I am trying to deconstruct it so that it looks like this.
{
name: 'Ritu',
status: 'active',
avatar: null,
avg_score: 100,
}
I tried using this const { _id:{...agent_info} } = user; but the output remains the same and the object is not altered.
>Solution :
Destructuring won’t alter the object. It might create a new object, but it won’t modify the original.
You can’t use a single destructuring operation to get the result you want. You can get close, but it takes two steps.
const { _id: { agent_info: { ...result } } } = original;
result.avg_score = original.avg_score;
Live Example:
const original = {
_id: {
agent_info: {
name: 'Ritu',
status: 'active',
avatar: null
}
},
avg_score: 100,
};
const { _id: { agent_info: { ...result } } } = original;
result.avg_score = original.avg_score;
console.log(result);
That copies everything from original._id.agent_info into a new object referenced by the result constant, then adds in avg_score.
You could also do it without reusing original, by grabbing avg_score in the same operation that creates result:
const { _id: { agent_info: { ...result } }, avg_score } = original;
result.avg_score = avg_score;
Live Example:
const original = {
_id: {
agent_info: {
name: 'Ritu',
status: 'active',
avatar: null
}
},
avg_score: 100,
};
const { _id: { agent_info: { ...result } }, avg_score } = original;
result.avg_score = avg_score;
console.log(result);
…but that leaves an avg_score constant lying around (which is harmless, but…).