如何在chrome.storage.sync.set中的对象中放置对象
我需要的结果是,因此我可以搜索值,然后提取名称和路径之类的数据
0:ID {
Name: Name of file
Path: Path Location
Enabled: true
}
1:ID{
Name: Name of file
Path: Path Location
Enabled: true
}
2:ID{
Name: Name of file
Path: Path Location
Enabled: true
}
我用过
var save = {};
save.id = {};
save.id.name = "Name of File";
save.id.path = "Path of File";
save.id.enable = "1";
chrome.storage.sync.set(save, function() {
console.log('Value is set to ' + save);
});
chrome.storage.sync.get(['save'], function(result) {
console.log('Value currently is ' + result.value);
});
但是它不起作用,我如何能够搜索ID,然后从该ID中提取相关数据?
您正在编写的键是'id'
,而不是'save'
。变量的名称与API无关(它甚至无法知道它)。重要的是变量的内容:它应该是一个对象,其中每个属性名称将是存储中的键,而每个属性值将是在该键下编写的内容。
这意味着您可以一次写入多个键:{key1: value1, key2: value2}
。
// two separate entries will be written to the storage
chrome.storage.sync.set({
id: {name: 'foo', path: 'bar', etc: ''},
herp: 'derp',
}, () => {
console.log('Value is set');
});
这也意味着您应该阅读'id'
,结果变量将包含id
作为属性,例如result.id
,而不仅仅是一些抽象的result.value
。
您还可以阅读多个键:['key1', 'key2']
将产生一个具有两个属性{key1: value1, key2: value2}
的变量,每个属性都可以通过result.key1
和result.key2
进行访问。
chrome.storage.sync.get(['id', 'herp'], result => {
console.log('Got data:', result, 'id:', result.id, 'herp:', result.herp);
});
并且不要在console.log中使用+
,因为它不会序列化对象的内容,而是使用,
。
另请参见: