[英]How can i convert an object in a specific format into another format
我很难尝试使用 javascript 将特定格式提供的对象从 API 转换为目标格式。 请注意,在目标格式中,不存在错误值。 这是故意的。 有人可以通过展示我如何进行这种转换来提供帮助。 谢谢
// Original format
const rules= [
{
dealer: {
view: true,
edit: false,
add: false
},
franchise: {
view: true,
edit: true,
add: true
},
branch: {
view: true,
edit: false,
add: false
}
}
]
// Target format
const rules = [
{
actions: ["view"],
subject: ["dealer"]
},
{
actions: ["view"],
subject: ["franchise"]
},
{
actions: ["edit"],
subject: ["franchise"]
},
{
actions: ["add"],
subject: ["franchise"]
},
{
actions: ["view"],
subject: ["branch"]
}
];
我实现了映射函数,它获取每个项目并根据值映射它如果为真
let rules = [
{
dealer: {
view: true,
edit: false,
add: false
},
franchise: {
view: true,
edit: true,
add: true
},
branch: {
view: true,
edit: false,
add: false
}
}
]
rules = rules.map(item => {
const keys = Object.keys(item);
let mappedItem = []
keys.forEach(key => {
for (const property in item[key]) {
if (item[key][property]) {
mappedItem.push({ subject: [key], actions: [property] })
}
}
})
return mappedItem;
});
let rules= [ { dealer: { view: true, edit: false, add: false }, franchise: { view: true, edit: true, add: true }, branch: { view: true, edit: false, add: false } } ]; const result = rules.map(obj => Object.keys(obj).map(k => ({ subject: [k], actions: Object.keys(obj[k]).filter(action => obj[k][action]) })).reduce((acc, cur) => ([ ...acc, ...cur.actions.map(a => ({subject: cur.subject, actions: [a]})) ]),[])) console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.