我有一个对象数组,作为数据响应的一部分,我通过每个对象的groupName键使用lodash的groupBy将它们分组在一起。
返回的一些项的groupName值为空、未定义或空字符串,并为这些值中的每个值创建单独的组。
我将所有的falsey组组合成一个单独的组名“未归类的”,并尝试删除原始的falsey组,只返回“未归类的”和所有其他真值组。
我遇到的问题是,我试图使用rest运算符来删除具有未定义的、空的和空字符串键的原始falsy对象,方法是将它们赋给像let groupKeysToRemove = ['undefined', 'null', '']这样的变量,然后像let { [groupKeysToRemove]: removed, ...groups } = initialGroups;一样尝试删除它们,但它返回相同的对象,但没有删除任何内容。我不确定是我的语法错误还是什么,但我被难住了。
通过sandbox编写代码
const resources = [
{
groupName: undefined,
name: "color organizer"
},
{
groupName: null,
name: "Bart_Simpson_200px"
},
{
groupName: "Spread Sheets",
name: "Backflow"
},
{
groupName: "Spread Sheets",
name: "220px-Marge_Simpson"
},
{
groupName: "",
name: "212px-Homer_Simpson_2006"
},
{
groupName: "Spread Sheets",
name: "Product 6"
},
{
groupName: "Warranties",
name: "Warranty Bart Simpson"
},
{
groupName: "Warranties",
name: "Warranty Product 2"
},
{
groupName: "Warranties",
name: "Warranty Product 3"
}
];
let initialGroups = groupBy(resources, "groupName");
let uncategorizedGroups = [];
uncategorizedGroups.push(...initialGroups[undefined], ...initialGroups[null], ...initialGroups[""]);
const renameGroups = uncategorizedGroups.map((object) => {
object.groupName = "Uncategorized";
return object;
});
const renamedGroups = groupBy(renameGroups, "groupName");
console.log('RENAMED GROUPS: ', renamedGroups)
const groupKeysToRemove = "undefined"
let { [groupKeysToRemove]: removed, ...groups } = initialGroups;
groups = { ...groups, ...renamedGroups };发布于 2021-06-05 04:41:06
可以将析构操作的括号语法[]看作是对象属性的索引,而不是您传入的数组。这类似于调用obj["a"]和obj.a来访问obj上的a字段。
因此,了解了这一点,您需要传入3个参数来提取您想要删除的值。对于null和undefined,我必须将它们放在单独的变量中,当直接将它们放在括号中时,它不起作用:
const nullKey = null;
const undefinedKey = undefined;
let {
[nullKey]: nullGroup,
[undefinedKey]: undefinedGroup,
[""]: emptyStringGroup,
...groups } = initialGroups;
groups = { ...groups, ...renamedGroups };
console.log("initialGroups: ", initialGroups);
console.log("GROUPS: ", groups);
console.log("null group", nullGroup)
console.log("undef group", undefinedGroup)
console.log("emptyStringGroup group", emptyStringGroup)https://stackoverflow.com/questions/67843389
复制相似问题