3 回答
TA贡献1825条经验 获得超4个赞
尝试检查数组的长度
const permissionData = [
{ group: [{ label: "Can View" }, { label: "Can Create" }] },
{ topgroup: [{ label: "Can View" }, { label: "Can Create" }] },
{ emptyGorup: [] }
];
let permissions =
permissionData &&
permissionData.reduce((a, b) => {
const onlyKey = Object.keys(b)[0];
if(b[onlyKey].length) {
a[onlyKey] = b[onlyKey].map(i => i.label);
}
return a;
}, {});
console.log(permissions)
TA贡献1856条经验 获得超17个赞
您可以扩展您当前的代码。获得对象后,您可以使用过滤器过滤掉带有空数组的键,并从过滤后的值再次构建对象
let obj = {
group: ["can view"],
topgroup: ["can view", "can create"],
emptygroup: []
}
let finalObj = Object.fromEntries(Object.entries(obj).filter(([key, value]) => Array.isArray(value) && value.length))
console.log(finalObj)
TA贡献1831条经验 获得超9个赞
您可以在 reduce 中添加条件:
let permissions =
permissionData &&
permissionData.reduce((a, b) => {
const onlyKey = Object.keys(b)[0];
if (a[onlyKey]) {
a[onlyKey] = b[onlyKey].map(i => i.value);
}
return a;
}, {});
添加回答
举报