0

我有以下实用方法:它删除有效负载对象的所有空键。

这是代码:

const removeEmptyKeysUtil = (payload: any): any => {
  Object.keys(payload).map(
    (key): any => {
      if (payload && payload[key] === '') {
        delete payload[key];
      }
      return false;
    }
  );
  return payload;
};

export default removeEmptyKeysUtil;

但我收到以下 eslint 错误:

分配给函数参数'payload'.eslint(no-param-reassign)的属性

有人建议我使用object destructuringObject.assign。但我对如何做到这一点有点困惑。

例如destructuring

      if (payload && payload[key] === '') {
         const {delete payload[key], ...actualPayload} = payload;
      }
      return false;

但我得到这个错误:

在声明之前使用的块范围变量“有效负载”。

我知道,我可以禁用该规则,但我不想这样做。我想正确编码该分支

你能帮我一点吗?我认为我根本不了解这两个概念。谢谢你。

4

2 回答 2

0

Lint 警告您要满足称为“不变性”的属性之一。

因此,当您收到要在此函数中使用的参数(它是一个对象)时,表明您从该函数返回的是一个带有您想要的修改的新对象,但这是一个新对象。

PD:此外,如果您使用 Typescript 并且知道该有效负载是由什么组成的,那么最好使用其数据创建一个接口而不是分配任何数据,因为它可以帮助您选择内部属性并避免错误,以及它将返回的响应。

一种解决方案可能是这样的:

const removeEmptyKeysUtil = (payload: any): any =>
  Object.keys(payload)
    .filter(key => payload[key] !== "")
    .reduce((result, key) => ({ ...result, [key]: payload[key] }), {});

export default removeEmptyKeysUtil;
于 2019-06-27T09:31:52.423 回答
0

我知道这个答案可能不是您想要的。由于您的代码在复杂对象上表现不佳,因此我创建了一个快速解决方案,它将提供您想要的结果。我希望它有所帮助。

function isEmptyObject(obj) {
  if (!obj || typeof obj !== 'object') return false;
  if (obj.constructor === Array) return obj.length === 0;
  return Object.keys(obj).length === 0 && obj.constructor === Object;
}

function removeEmptyKeysUtil(obj) {
  if (!obj) return {};
  Object.keys(obj).map(key => {
    // Add additional check here for null, undefined, etc..
    if (obj[key] === '') delete obj[key]; 

    if (obj.constructor === Object) {
      obj[key] = removeEmptyKeysUtil(obj[key])
    }

    if (obj.constructor === Array) {
      for (let i = obj.length; i >= 0; i--) {
        obj[i] = removeEmptyKeysUtil(obj[i])
        if (isEmptyObject(obj[i])) {
          obj.splice(i, 1);
        }
      }
    }

    if (isEmptyObject(obj[key])) {
      delete obj[key];
    }
  })
  return obj;
}

const obj = {
  test: '11',
  test1: '1',
  test2: {
    test: '',
    test1: ''
  },
  test3: [
    {
      test: ''
    },
    {
      test: ''
    },
    {
      test: '3'
    },
    {
      test33: {
        test: '1',
        test1: ''
      }
    }
  ]
};

console.log(removeEmptyKeysUtil(obj))

于 2019-06-27T11:25:52.260 回答