问题描述
我正在尝试通过express发送一个React组件树,我的组件数组包含关键的 >
const obj1 = { 'stringKey': Symbol.for('String Value'), boolKey: true, numKey: 1 } const obj2 = {...obj1, 'stringKey': 'Plain String'} console.log(JSON.stringify(obj1, (name, value) => { if(typeof value === 'symbol') { value = `$$${Symbol.keyFor(value)}` } return value })) console.log(JSON.stringify(obj2))
天真演示.您最好将清单中的道具从清单中恢复为符号.
const a = {a: Symbol.for('a')} const str = JSON.stringify(a, (k,v) => typeof v === 'symbol' ? `$$Symbol:${Symbol.keyFor(v)}` : v) const b = JSON.parse(str, (k,v) => { const matches = v.match && v.match(/^\$\$Symbol:(.*)$/) return matches ? Symbol.for(matches[1]) : v }) console.log(a, str, b, a.a === b.a)
I'm attempting to send a React component tree via express and my array of components includes the critical $$typeof: Symbol.for('react.element') property. I'm using res.send. The rest of the object comes through except for that property. I've been advised it may have to do with Symbol.for not being enumerable? JSON.stringify also strips the property.
I've narrowed the issue down to being properties that have Symbol values. This is reflected in the documentation for stringify.. Can anyone explain why that's the case or what a workaround is?
const obj1 = { 'stringKey': Symbol.for('String Value'), boolKey: true, numKey: 1 } const obj2 = {...obj1, 'stringKey': 'Plain String'} console.log(JSON.stringify(obj1)) console.log(JSON.stringify(obj2))
Since the symbol is used as value you could use custom replacer that formats Symbol to a string you could restore on receiving side using custom reviver
const obj1 = { 'stringKey': Symbol.for('String Value'), boolKey: true, numKey: 1 } const obj2 = {...obj1, 'stringKey': 'Plain String'} console.log(JSON.stringify(obj1, (name, value) => { if(typeof value === 'symbol') { value = `$$${Symbol.keyFor(value)}` } return value })) console.log(JSON.stringify(obj2))
Naive demo. You could better whilelist props that should be restored as symbols from registry.
const a = {a: Symbol.for('a')} const str = JSON.stringify(a, (k,v) => typeof v === 'symbol' ? `$$Symbol:${Symbol.keyFor(v)}` : v) const b = JSON.parse(str, (k,v) => { const matches = v.match && v.match(/^\$\$Symbol:(.*)$/) return matches ? Symbol.for(matches[1]) : v }) console.log(a, str, b, a.a === b.a)
这篇关于Stringify删除了具有Symbol属性的JavaScript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!