如何在序列化对象时省略 javascript 或打字稿中的“未定义”列

How to omit `undefined` column in javascript or typescript when serialization object

我有这样的对象:

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.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));

而不是省略,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>

这可能是您定义 class 时的问题。我复制了它仍然有效。以下代码段可以帮助您

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>