假设我使用Immutable.js定义了以下记录:
var Address = Immutable.Record({street: '', city: '', zip: ''});
var User = Immutable.Record({name: '', address: new Address()});
如何将普通javascript对象转换为用户记录?我尝试了以下但它没有产生预期的输出:
var user = new User({name: 'Foo', address: {street: 'Bar', city: 'Baz'}});
// => Record { "name": "Foo", "address": [object Object] }
我知道可以显式创建地址记录:
var user = new User({name: 'Foo', address: new Address({street: 'Bar', city: 'Baz'})});
// => Record { "name": "Foo", "address": Record { "street": "Bar", "city": "Baz", "zip": "" } }
但这不是我要找的解决方案。想象一下,你有记录嵌套了几个级别,并希望以JSON形式存储/检索数据(例如在数据库中)。我想使用实际的用户记录结构作为重新创建嵌套记录的模式信息。或者有更好的方法来表示嵌套和结构化的不可变数据吗?
答案 0 :(得分:9)
记录结构的预期用途不是验证提供的数据的结构,只是为了确定允许的密钥集,如果没有给出,则提供默认值。
因此,使用您的示例,如果您在不提供地址的情况下初始化记录,您将获得地址的正确Immutable.Record对象:
var user = new User({name: 'Foo'});
// => Record { "name": "Foo", "address": Record { "street": "", "city": "", "zip": "" } }
实现您想要的一种 hackish 方法是使用自定义Immutable.fromJS
函数在reviver
方法上编写包装器:
Immutable.Record.constructor.prototype.fromJS = function(values) {
var that = this;
var nested = Immutable.fromJS(values, function(key, value){
if(that.prototype[key] && that.prototype[key].constructor.prototype instanceof Immutable.Record){return that.prototype[key].constructor.fromJS(value)}
else { return value }
});
return this(nested);
}
然后你可以像这样使用它:
var user = User.fromJS({name: 'Foo', address: {street: 'Bar', city: 'Baz'}});
// => User { "name": "Foo", "address": Record { "street": "Bar", "city": "Baz", "zip": "" } }
但是,如果您想正确检查数据结构,我建议将Immutable.js与一些静态类型检查器一起使用,例如http://flowtype.org/或http://www.typescriptlang.org/
答案 1 :(得分:9)
您可以使User
子类化Record
定义并在构造函数中解析address
:
import {Record} from 'immutable'
const Address = Record({street: '', city: '', zip: ''});
class User extends Record({name: '', address: new Address()}) {
constructor({name, address} = {}) {
super({name, address: new Address(address)})
}
}
const user = new User({
name: 'Andy',
address: {
street: 'wherever',
city: 'Austin',
zip: 'TX'
}
})
console.log(user)
console.log('user.address instanceof Address:', user.address instanceof Address)
const user2 = new User({name: 'Bob'})
console.log(user2)
console.log('user2.address instanceof Address:', user2.address instanceof Address)
输出:
User { "name": "Andy", "address": Record { "street": "wherever", "city": "Austin", "zip": "TX" } }
user.address instanceof Address: true
User { "name": "Bob", "address": Record { "street": "", "city": "", "zip": "" } }
user2.address instanceof Address: true