Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Destructuring an object in order to make the all properties none nested / single level

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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…).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading