首页 > 解决方案 > 下一个 ES 中的对象映射

问题描述

我有一个带有状态属性的对象数组:

[{
...
status: 'enable'
},{
...
status: 'enable'
}...]

status 属性可以有 2 个值:'enable'/'disable'.

如果状态为“启用”,我想将其设置为禁用,反之亦然。

而不是执行以下操作:

if(obj.status === 'enable') 
    obj.status = 'disable'
else 
    obj.status = 'enable'

我想将启用状态映射到一个真正的布尔值(并禁用到 false)并执行以下操作:

Mapping[obj.status] = !Mapping[obj.status] // this should change the status value

可能吗?

标签: javascriptecmascript-6ecmascript-next

解决方案


您可以使用一个对象来更改值。

const change = { enable: 'disable', disable: 'enable' };

// in loop
obj.status = change[obj.status];

推荐阅读