首页 > 解决方案 > 尝试创建字符串数组以在解构函数中使用以删除对象属性,只有单个字符串值有效

问题描述

我有一个对象数组作为数据响应的一部分,我groupBy通过每个对象的 groupName 键使用 lodash 将它们分组在一起。

返回的一些项目的groupName值为 null、未定义或空字符串,lodash 为每个值创建单独的组。

我将所有虚假组组合成一个组名“未分类”并尝试删除原始虚假组以仅返回“未分类”和所有其他真实组。

我遇到的问题是我正在尝试使用 rest 运算符来删除具有未定义、null 和空字符串键的原始 falsy 对象,方法是将它们分配给变量 likelet groupKeysToRemove = ['undefined', 'null', '']然后尝试删除它们 likelet { [groupKeysToRemove]: removed, ...groups } = initialGroups;但它返回相同的对象,没有删除任何内容。我不确定我的语法是错误的还是什么,但我很困惑。

通过沙箱代码:

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 };

标签: javascriptarraysobject

解决方案


将破坏操作的括号语法 视为对象属性的索引,而不是您传入的数组。[]这类似于调用 example obj["a"]vsobj.a来访问a.obj

所以知道这一点,您需要传入 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)

推荐阅读