Basil Thaddeus
Basil Thaddeus

Reputation: 71

Accessing the first value of the first key in an object

I am having a little bit of an issue trying to get the value of a certain object. Since this is a bit hard to explain, I'll set up a scenario that follows what I need.

{"Gmail": {"[email protected]": "password1", "[email protected]": "password2}, ...}

I have an object (as represented above, we will call the object "encrypted"). I can get the value "Gmail" by using Object.keys(encrypted)[i] where i represents the index I'm looking for. The issue I am encountering is, how do I get [email protected] or password1?

I've been aimlessly wandering around it for a while trying to figure this out, searching for answers, but I can't seem to do so or find any that aren't based on arrays. Any help is great, thank you!

Upvotes: 0

Views: 68

Answers (1)

You could use Object.entries

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

This turns objects into arrays of key - value which you can traverse, an example would be something like:

const data = {
    "Gmail": { "[email protected]": "password1", "[email protected]": "password2" },
    "Gmail2": { "[email protected]": "password1", "[email protected]": "password2" },
};


Object.entries(data).forEach(([key, value]) => {
    const emailProvider = key;
    const emailList = Object.entries(value);

    console.log({ mail: emailProvider });

    emailList.forEach(([email, password]) => {
        console.log({ email, password })
    })
});

Upvotes: 2

Related Questions