gpt4 book ai didi

具有 Symbol 属性的 JavaScript 对象被 Stringify 移除

转载 作者:行者123 更新时间:2023-11-30 21:21:25 26 4
gpt4 key购买 nike

我正在尝试通过 express 发送 React 组件树,我的组件数组包含关键的 $$typeof: Symbol.for('react.element') 属性。我正在使用 res.send。除该属性外,对象的其余部分都通过了。我被告知它可能与 Symbol.for 不可枚举有关? JSON.stringify 也去除了属性。

我已将问题缩小到具有 Symbol 值的属性。这反射(reflect)了in the documentation for stringify. .谁能解释为什么会这样或解决方法是什么?

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))

简单的演示。你最好 whilelist 应该从注册表中恢复为符号的 Prop 。

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)

关于具有 Symbol 属性的 JavaScript 对象被 Stringify 移除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45152582/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com