Home > database >  (Javascript) Is it possible the Object.keys() return a list of objects?
(Javascript) Is it possible the Object.keys() return a list of objects?

Time:10-27

I want acess the keys of a object but those keys are objects too.

const caio = new Person("Caio")
const rafael = new Person("Rafael")

const expense = {caio: 10, rafael: 0}

console.log(Object.keys(expense))
#result ['caio', 'rafael']

I would want to acess the objects caio/rafael (Person objects). Is it possible?

CodePudding user response:

Without eval, I don't think you can do it dynamically in a safe way. But you could have a "map" to do this that uses shorthand initialization:

class Person { constructor(name) { this.name = name; } }

const caio = new Person("Caio")
const rafael = new Person("Rafael")

const pplmap = { caio, rafael };

const expense = {caio: 10, rafael: 0}

console.log(Object.keys(expense).map((p) => pplmap[p]));

CodePudding user response:

JS objects can only have string or symbol as keys so that's not possible.

On the other hand, a Map can have object keys so you may use one instead:

const expenses = new Map();
expenses.set(caio, 10);
expenses.set(raphael, 0);
const personIterator = expenses.keys() // will return an iterator of the keys
Array.from(personIterator) // an array containing the keys
  • Related