Stringify删除了具有Symbol属性的JavaScript对象 [英] JavaScript object with Symbol property get's removed by Stringify
问题描述
我正在尝试通过express发送一个React组件树,我的组件数组包含关键的$$typeof: Symbol.for('react.element')
属性.我正在使用res.send
.除该属性外,对象的其余部分都会通过.有人建议我,它可能与Symbol ..不能枚举有关? JSON.stringify
也会删除该属性.
我将问题缩小为具有Symbol
值的属性. stringify
的文档中反映出来. /a>.任何人都可以解释为什么是这种情况或解决方法吗?
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))
由于将符号用作值,因此可以使用将符号格式化为字符串的自定义replacer
,您可以使用自定义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))
天真演示.您最好将清单中的道具从清单中恢复为符号.
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对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!