我有这样的对象:
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.这个栏目是动态的,不能像我一样预测某个栏目。
发布于 2020-09-09 11:28:37
在这方面,最好使用pickBy和omitBy,而不是省略:
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>
发布于 2020-09-09 11:22:28
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));
发布于 2020-09-09 11:58:46
在定义类时,这可能是问题所在。我复制了它,它仍然可以工作。下面的代码片段可以帮助你
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>
https://stackoverflow.com/questions/63804261
复制相似问题