0

How do I place an Object within an Object within chrome.storage.sync.set

The outcome I'm needing is, so I can then search the Value and then pull the data like name and path

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
}

I've used

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

But its not working, how would I be able to search the ID and then pull the relevant data from that ID?

kire38
  • 75
  • 8

1 Answers1

1

The key you're writing is 'id', not 'save'. The name of the variable doesn't matter to the API (it has no way of even knowing it). The important thing is the contents of the variable: it should be an object where each property name will be a key in the storage, and each property value will be the contents written under that key.

It means you can write multiple keys at once: {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');
});

It also means you should read 'id', and the result variable will contain id as a property e.g. result.id, not just some abstract result.value.

You can also read multiple keys: ['key1', 'key2'] will produce a variable with two properties {key1: value1, key2: value2} each accessible as result.key1 and result.key2.

chrome.storage.sync.get(['id', 'herp'], result => {
  console.log('Got data:', result, 'id:', result.id, 'herp:', result.herp);
});

And don't use + in console.log because it won't serialize the contents of objects, instead use ,.

See also:

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • This is perfect, thank you :D I also used JSON.parse to place the object so it can be stringify within the sync.set – kire38 Nov 22 '19 at 16:21
  • Technically there's no need for JSON.parse/stringify because it's already done internally. – wOxxOm Nov 22 '19 at 16:32