Charles Semaan
Charles Semaan

Reputation: 273

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.

Upvotes: 1

Views: 894

Answers (2)

Ran Turner
Ran Turner

Reputation: 18076

You can achieve this object destructuring using something that is called deep property. enter image description here

const obj = {
  _id: {
    agent_info: {
      name: 'Ritu',
      status: 'active',
      avatar: null
    }
  },
  avg_score: 100,
};

const {_id:{ agent_info:{ ...res }}} = obj;
res["avg_Score"] = obj.avg_score;

console.log(res);

Check out the this link for more info

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074585

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

Upvotes: 1

Related Questions