[英]Destructuring an object in order to make the all properties none nested / single level
我有这个 object 具有以下嵌套属性。
{
_id: {
agent_info: {
name: 'Ritu',
status: 'active',
avatar: null
}
},
avg_score: 100,
}
我试图解构它,使它看起来像这样。
{
name: 'Ritu',
status: 'active',
avatar: null,
avg_score: 100,
}
我尝试使用这个const { _id:{...agent_info} } = user;
但是 output 保持不变,object 没有改变。
解构不会改变 object。 它可能会创建一个新的 object,但不会修改原始文件。
您不能使用单个解构操作来获得您想要的结果。 你可以靠近,但需要两个步骤。
const { _id: { agent_info: { ...result } } } = original;
result.avg_score = original.avg_score;
现场示例:
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);
这会将original._id.agent_info
中的所有内容复制到由result
常量引用的新 object 中,然后添加avg_score
。
您也可以在不重用original
的情况下执行此操作,方法是在创建result
的同一操作中获取avg_score
:
const { _id: { agent_info: { ...result } }, avg_score } = original;
result.avg_score = avg_score;
现场示例:
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);
...但这会留下一个avg_score
常数(这是无害的,但是...)。
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);
查看此链接以获取更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.