【问题标题】:How to omit `undefined` column in javascript or typescript when serialization object序列化对象时如何在javascript或打字稿中省略“未定义”列
【发布时间】:2020-09-09 03:15:58
【问题描述】:

我有这样的对象:

Person {
  id: '75c37eb9-1d88-4d0c-a927-1f9e3d909aef',
  user: undefined,
  title: 'Mr.',
  first_name: 'somebody',
  last_name: 'body',
  belong_organization: undefined,
  expertise: [],
  contact: undefined
}

当我进行序列化时,我使用 loadsh 省略函数,例如:

toJSON() {
    return _.omit(this, ['contact']);
}

我想要做的是省略未定义的属性,因为错误:

 `undefined` cannot be serialized as JSON.

列是动态的,不能像我一样预测某些列。

【问题讨论】:

  • 使用JSON.parse。它会自动执行此操作。

标签: javascript json typescript undefined


【解决方案1】:

而不是省略,pickByomitBy 更可取:

var person = {
  id: '75c37eb9-1d88-4d0c-a927-1f9e3d909aef',
  user: undefined,
  title: 'Mr.',
  first_name: 'somebody',
  last_name: 'body',
  belong_organization: undefined,
  expertise: [],
  contact: undefined
};

const newPerson= _.pickBy(person, v => v !== undefined);

console.log(newPerson);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>

【讨论】:

    【解决方案2】:

    JSON.stringify 将省略未定义的属性,无需任何特殊逻辑。

    console.log(JSON.stringify({
      id: '75c37eb9-1d88-4d0c-a927-1f9e3d909aef',
      user: undefined,
      title: 'Mr.',
      first_name: 'somebody',
      last_name: 'body',
      belong_organization: undefined,
      expertise: [],
      contact: undefined
    }, null, 3));

    【讨论】:

      【解决方案3】:

      定义类时可能会出现问题。我复制了它仍然有效。下面的sn-p可以帮助你

      class Person {
        constructor(props) {
          Object.assign(this, props)
        }
      
        toJSON() {
          return _.omit(this, ["contact"])
        }
      }
      
      const person = new Person({
        id: "75c37eb9-1d88-4d0c-a927-1f9e3d909aef",
        user: undefined,
        title: "Mr.",
        first_name: "somebody",
        last_name: "body",
        belong_organization: undefined,
        expertise: [],
        contact: undefined,
      })
      
      console.log(person.toJSON())
      <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-04
        • 2015-05-26
        • 2022-11-22
        • 2021-07-01
        • 1970-01-01
        • 2010-09-14
        • 2011-11-23
        • 1970-01-01
        相关资源
        最近更新 更多