SteinTech
SteinTech

Reputation: 4068

How to get the name of the key of an object

How can I get the name of the key name of an object?

In the example I want key to equal a, b and c.

let demo = { "a": valA, "b": valB, "c": valC };

$.each(demo, function (index, val) {
    let key = ??
});

Upvotes: 1

Views: 87

Answers (2)

Michael Evans
Michael Evans

Reputation: 1011

Since you're using ES6 syntax, you have access to the for ... in loop, which can loop through objects.

const demo = { "a": valA, "b": valB, "c": valC };

for (const key in demo) {
  console.log(key);
}

// a
// b

Upvotes: 2

Ori Drori
Ori Drori

Reputation: 191946

Use Object#keys:

const demo = { "a": "valA", "b": "valB", "c": "valC" };

const keys = Object.keys(demo);

console.log(keys);

Upvotes: 2

Related Questions