Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG: The Map type is not saved to a file #603

Open
borbiuk opened this issue May 11, 2023 · 2 comments
Open

BUG: The Map type is not saved to a file #603

borbiuk opened this issue May 11, 2023 · 2 comments

Comments

@borbiuk
Copy link

borbiuk commented May 11, 2023

const db = new JsonDB(
    new Config('db.json', true, true)
);

const map = new Map();
map.set('a', 1);
map.set('b', 2);
map.set('c', 3);

await db.push('pathToMap', map);

const beforeReload = await db.getData('/'); //OK but pathToMap in file is empty

await db.reload();

const afterReload = await db.getData('/'); //returns: { pathToMap: {} }
@borbiuk borbiuk changed the title The Map type is not saved to a file BUG: The Map type is not saved to a file May 11, 2023
@Tijawk
Copy link

Tijawk commented Jun 16, 2023

I think it's not a bug. A Map cannot be converted to JSON natively.

const map = new Map();
map.set('a', 1);
map.set('b', 2);
map.set('c', 3);

JSON.stringify(map) // return '{ }'

You should convert your map into object to save it.

Given in MDN, fromEntries() is available since Node v12:

const map1 = new Map([
['foo', 'bar'],
['baz', 42]
]);

const obj = Object.fromEntries(map1);
// { foo: 'bar', baz: 42 }
For converting object back to map:

const map2 = new Map(Object.entries(obj));
// Map(2) { 'foo' => 'bar', 'baz' => 42 }

source: https://stackoverflow.com/a/55537385

@stefnotch
Copy link

Yeah, for serializing a map, one would have to do something like this
https://stackoverflow.com/questions/29085197/how-do-you-json-stringify-an-es6-map/73155667#73155667

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants