Search code examples
javascriptobject

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


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?


Solution

  • 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