Closed Industrial closed 8 years ago
Hi,
tcomb's instances are immutables (actually frozen) in development. You can change the format while you are serialising to JSON:
// say this is the type you are using in the form...
const Person = t.struct({
name: t.String,
birthDate: t.Date
}, 'Person')
// ...and this is the value returned by the form
const person = new Person({
name: 'Giulio',
birthDate: new Date(1973, 10, 30)
})
// by default dates are formatted to ISO strings...
console.log(JSON.stringify(person)) // => {"name":"Giulio","birthDate":"1973-11-29T23:00:00.000Z"}
// ... or using a replacer
console.log(JSON.stringify(person, function (k, v) {
if (k === 'birthDate') {
return v.substring(0, 4)
}
return v
})); // => {"name":"Giulio","birthDate":"1973"}
or copy the immutable object to a mutable one with Object.assign
.
If your date is deeply nested you could use the immutability helpers https://github.com/gcanti/tcomb/blob/master/docs/API.md#updating-immutable-instances to make a copy:
console.log(t.update(person, {
birthDate: { $set: person.birthDate.getFullYear() }
})); // => Object {name: "Giulio", birthDate: 1973}
Okay, that's the approach I'm using now (JSON.parse(JSON.stringify(struct))
). Thanks :)
Hi.
I need to change some of the data that comes out of a Struct out of a
.getValue()
. I really was expecting a plain object here. I am trying to send ti to the backend but I need to change some date formatting. I'm getting the error that a struct is read-only.How do I change the getValue() data into a plain object, so I can serialize it into JSON how I want?