简体   繁体   English

解构 object 以使所有属性都没有嵌套/单级

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

I have this object with the following nested properties.我有这个 object 具有以下嵌套属性。

{
  _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;我尝试使用这个const { _id:{...agent_info} } = user; but the output remains the same and the object is not altered.但是 output 保持不变,object 没有改变。

Destructuring won't alter the object.解构不会改变 object。 It might create a new object, but it won't modify the original.它可能会创建一个新的 object,但不会修改原始文件。

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 .这会将original._id.agent_info中的所有内容复制到由result常量引用的新 object 中,然后添加avg_score

You could also do it without reusing original , by grabbing avg_score in the same operation that creates result :您也可以在不重用original的情况下执行此操作,方法是在创建result的同一操作中获取avg_score

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...). ...但这会留下一个avg_score常数(这是无害的,但是...)。

You can achieve this object destructuring using something that is called deep property.您可以使用称为深度属性的东西来实现此 object 解构。 在此处输入图像描述

 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查看此链接以获取更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM