我检索以下字符串值数组
[
"Module1.resource1.create",
"Module1.resource1.read",
"Module1.resource1.update",
"Module1.resource1.delete",
...
"Module1.resourceN.create",
"Module1.resourceN.read",
"Module1.resourceN.update",
]
我想把它们改成这样的json格式
{"privileges": {
"Module1": {
"resource1": {
"create": true,
"read": true,
"update": true,
"delete": true,
},
...
"resourceN": {
"create": true,
"read": true,
"update": true,
}
}
}
}
我能想到的就是为每个字符串运行一个循环,使用 split(".")
然后以某种方式将其更改为 json 对象。我遇到的问题是 json 不是一个简单的 key: value
,它更像是一个 key: object: object: object: value
如果这有意义的话。 ..
我很感激在正确方向上的插入。
干杯
最佳答案
您可以使用 Array#reduce
方法:
const result = { privileges: {} };
items.reduce((ret, el) => {
// Split the array elements and use destructuring assignment syntax for
// creating constants
const [module, resource, verb] = el.split('.');
// check if privileges[module] property exists. If not, define it as an empty object.
if (!ret[module]) ret[module] = {};
// follows the previous line's logic for resources!
if (!ret[module][resource]) ret[module][resource] = {};
ret[module][resource][verb] = true;
return ret;
}, result.privileges);
关于javascript - 将字符串更改为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52100309/