如何在 Chrome 应用程序中存储地图对象?
How can I store a Map object in a Chrome App?
使用Chrome API chrome.storage.local,我可以保存并成功检索数组,但我无法检索地图对象。
var folders = new Map()
//... populate Map
chrome.storage.local.set( { "myFolders": folders } )
chrome.storage.local.get( "myFolders", function ( saved )
{
console.assert( typeof saved.myFolders.size === 'number', "not a Map!" )
} )
在存储之前,我被迫将Map转换为Array。我可以直接存储 Map 对象吗?
不,您不能存储或传递不可 JSON 序列化的对象(DOM 节点是另一个常见示例)。
而 Map
不是:
> JSON.stringify(new Map().set("a", "b"))
"{}"
因此,您只能存储 JSON can encode。这意味着您必须在存储访问之上执行您自己的 serialization/deserialization。
编辑:如 Simon 的回答所示,Chrome 比 JSON 执行更精细的序列化(保留 RegExp 和 Date),但原则仍然成立:非原始对象需要自定义序列化。
嗯,检查 documentation:
Primitive values such as numbers will serialize as expected. Values
with a typeof "object" and "function" will typically serialize to {},
with the exception of Array (serializes as expected), Date, and Regex
(serialize using their String representation).
所以你不能在不转换数据的情况下直接这样做。
您不能 JSON.stringify 地图,因此它不能像预期的那样开箱即用。然而,问题是“如何”,所以这里是:
var folders = new Map()
//... populate Map
// save
chrome.storage.local.set(
{ "myFolders": Object.fromEntries(folders) }
)
// load
chrome.storage.local.get( "myFolders",
function(saved){
folders = new Map(Object.entries(result.myFolders));
console.log(folders);
}
)
请记住 API 是异步的,因此 folders
将在 chrome.storage.local.get
调用结束后加载。
使用Chrome API chrome.storage.local,我可以保存并成功检索数组,但我无法检索地图对象。
var folders = new Map()
//... populate Map
chrome.storage.local.set( { "myFolders": folders } )
chrome.storage.local.get( "myFolders", function ( saved )
{
console.assert( typeof saved.myFolders.size === 'number', "not a Map!" )
} )
在存储之前,我被迫将Map转换为Array。我可以直接存储 Map 对象吗?
不,您不能存储或传递不可 JSON 序列化的对象(DOM 节点是另一个常见示例)。
而 Map
不是:
> JSON.stringify(new Map().set("a", "b"))
"{}"
因此,您只能存储 JSON can encode。这意味着您必须在存储访问之上执行您自己的 serialization/deserialization。
编辑:如 Simon 的回答所示,Chrome 比 JSON 执行更精细的序列化(保留 RegExp 和 Date),但原则仍然成立:非原始对象需要自定义序列化。
嗯,检查 documentation:
Primitive values such as numbers will serialize as expected. Values with a typeof "object" and "function" will typically serialize to {}, with the exception of Array (serializes as expected), Date, and Regex (serialize using their String representation).
所以你不能在不转换数据的情况下直接这样做。
您不能 JSON.stringify 地图,因此它不能像预期的那样开箱即用。然而,问题是“如何”,所以这里是:
var folders = new Map()
//... populate Map
// save
chrome.storage.local.set(
{ "myFolders": Object.fromEntries(folders) }
)
// load
chrome.storage.local.get( "myFolders",
function(saved){
folders = new Map(Object.entries(result.myFolders));
console.log(folders);
}
)
请记住 API 是异步的,因此 folders
将在 chrome.storage.local.get
调用结束后加载。