1

I'm using the flat-cache NPM package and I'm currently blocked because I can't recover the key from the data I'm caching. It must be very simple, but I'm starting with the JS and I'm pulling my hair out on this problem.

Simple example of code :

main.js

var flatCache = require('flat-cache')
flatCache.setKey('d86f003c-bf0a-4b08-9744-1081c78ece9d', {"creation":"2018/02/20", "link":"https://www.npmjs.com/package/uuid","comment":"UUID", "tags":["NPM", "UUID"]});
var a = flatCache.all();
console.log(a);

Example of data from console :

{
    "d86f003c-bf0a-4b08-9744-1081c78ece9d": {
        "date":"20180220", 
        "comment":"Hello world",
        "tags":[
            "hello", 
            "worlds"
        ]
    }
}

What would be the procedure to follow to retrieve the key : d86f003c-bf0a-4b08-9744-1081c78ece9d ?

Thank you in advance for your answer !

3
  • 1
    a["d86f003c-bf0a-4b08-9744-1081c78ece9d"] Commented Feb 21, 2018 at 13:46
  • 1
    Can't you use flatCache.getKey('d86f003c-bf0a-4b08-9744-1081c78ece9d') instead of all()? Commented Feb 21, 2018 at 13:46
  • I wish to obtain the key and not the data associated with the key. Like I made a loop on each element and retrieved the key to set it in an another object or something like this Commented Feb 21, 2018 at 13:50

1 Answer 1

9

Use Object.keys method.

In your case:

// `a` is defined somewhere there
...
Object.keys(a); // an array of object keys - but only the first level
console.log(Object.keys(a)[0]); // should log `d86f003c-bf0a-4b08-9744-1081c78ece9d`

for further reference - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Sign up to request clarification or add additional context in comments.

1 Comment

Ah yes ! That's it, thank you ! I couldn't explain it correctly and so I couldn't find a solution, but thanks to you it's good!