Open iamisti opened 2 years ago
我也遇到了这个问题,在我的场景下,friends
属性的值可能为undefined
或complex array
或empty array
,这三种情况需要在serializer执行不同的处理方式
我需要类似于friends: undefined | array
的声明,然而我并没有找到很好的实现方案。但是我只能在代码中保证friends的值不为undefined
,而是一个空数组,下面是我的解决方案:
[
{ "id": 1, "friends": [{ "id": 5 }] },
{ "id": 2, "friends": [] },
{ "id": 3, "friends": undefined }
]
const stringify = sjs({
data: attr(
'array',
sjs({
id: attr('number'),
friends: attr('array', (d) => {
// when friends is [], d is undefined
if (!d) return ''
// pass d to sjs and transfer it to plain string
else return sjs({ id: attr('number') })(d)
})
})
)
})
stringify({
data: [
{ id: 1, friends: [] },
{ id: 2, friends: [{ id: 1 }] }
// { id: 3, friends: undefined }
]
})
How do you deal with a JSON that can have a property that has a type of object or null?
So basically: { something: MyObject || null }
how do you define the serializer?