List the properties of an object in JavaScript
Beginner · 3 min read
An object in JavaScript is a bag of named values. A student record might hold a name, a class and a roll number. Very often you need just the names of those values, the keys: to build a table header, to check a form has every field, or to print a quick summary while you debug.
In this tutorial you will turn { name: 'David Rayy', sclass: 'VI', rollno: 12 } into the text name,sclass,rollno. You will learn Object.keys, join, and the older for...in loop, and you will see the one case where those two give different answers. You only need to know how to write an object and a function.
Keys and values
Each entry in an object is a pair: a key on the left of the colon and a value on the right.
const student = { name: 'David Rayy', sclass: 'VI', rollno: 12 };
console.log(student.name); // David Rayy
console.log(student.rollno); // 12
Here the keys are name, sclass and rollno. The keys the object holds itself are called its own properties. An object can also borrow properties from another object, called its prototype. Those borrowed ones are inherited properties. That difference matters later in this lesson.
Arrays of text and join
join takes an array and glues its items into one string, with whatever you pass between them:
console.log(['a', 'b', 'c'].join(',')); // a,b,c
console.log(['a', 'b', 'c'].join(' - ')); // a - b - c
So if you can get the keys as an array, one join call finishes the job.
Here is the exercise. Try it on your own first if you like, then read on and we will build it together.
1 List the properties of an object
easyGiven { name: 'David Rayy', sclass: 'VI', rollno: 12 }, produce name,sclass,rollno.
Stuck? Three hints, smallest first
- 1.
Object.keysgives an array of the own, enumerable keys. - 2.
join(‘,’)turns that array into the string the question asks for. - 3.
for...inalso walks inherited keys, which is usually not what you want.
Step 1: get the keys as an array
Object.keys takes an object and hands back an array of its own keys:
console.log(Object.keys(student)); // [ 'name', 'sclass', 'rollno' ]
The keys come out in the order you wrote them. That is the order the expected output uses.
Step 2: join them with commas
Put the two ideas together in a small arrow function:
const listProperties = (obj) => Object.keys(obj).join(',');
console.log(listProperties(student)); // name,sclass,rollno
console.log(listProperties({})); // an empty string
An empty object has no keys, so Object.keys gives [], and joining an empty array gives ''. No special case needed.
Step 3: the older way, for...in
Before Object.keys existed, people looped over an object with for...in. It visits each key in turn, so you can push them into an array yourself:
function listByForIn(obj) {
const keys = [];
for (const key in obj) keys.push(key);
return keys.join(',');
}
console.log(listByForIn(student)); // name,sclass,rollno
Same answer. So why prefer Object.keys? Because the two only agree while nothing is inherited.
Step 4: add an inherited property
Object.create(base) makes a new, empty object whose prototype is base. The new object can read everything in base without holding it itself.
const base = { fare: 4500 };
const trip = Object.create(base);
trip.plate = 'LAG-441-XA';
console.log(trip.fare); // 4500
console.log(Object.hasOwn(trip, 'fare')); // false
console.log(Object.hasOwn(trip, 'plate')); // true
trip.fare works, but Object.hasOwn tells you fare is not one of trip's own properties. It lives on base. Now list the keys both ways:
console.log(listProperties(trip)); // plate
console.log(listByForIn(trip)); // plate,fare
Object.keys lists own keys only. for...in also walks up to the prototype and picks up fare. Most of the time you want the first behavior, which is why Object.keys is the usual answer.
Step 5: a surprise in the key order
Keys normally keep the order you added them. Keys that look like whole numbers are the exception: they move to the front, in number order.
console.log(Object.keys({ b: 1, 2: 2, a: 3, 1: 4 })); // [ '1', '2', 'b', 'a' ]
Notice the numbers also come back as strings. Every object key is a string (or a symbol). If you need strict insertion order for any kind of key, a Map keeps it.
The full solution
The panel defines both versions, prints them for the student, then repeats the test with the inherited fare so you can see the two disagree. Press Run to see the output.
const student = { name: 'David Rayy', sclass: 'VI', rollno: 12 };
const listProperties = (obj) => Object.keys(obj).join(',');
// for...in walks the prototype chain too. Same answer here, different answer
// as soon as anything is inherited.
function listByForIn(obj) {
const keys = [];
for (const key in obj) keys.push(key);
return keys.join(',');
}
// Something with an inherited property, to show the difference.
const base = { fare: 4500 };
const trip = Object.create(base);
trip.plate = 'LAG-441-XA';
console.log('Object.keys :', listProperties(student));
console.log('for...in :', listByForIn(student));
console.log('--- with an inherited property ---');
console.log('Object.keys :', listProperties(trip), '<- own only');
console.log('for...in :', listByForIn(trip), '<- includes the inherited fare');
Output
10 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 10 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test("the expected output", listProperties(student), 'name,sclass,rollno');
test('the keys come out in insertion order', Object.keys(student), ['name', 'sclass', 'rollno']);
test('for...in agrees when nothing is inherited', listByForIn(student), listProperties(student));
test('an empty object gives an empty string', listProperties({}), '');
test('Object.keys sees only own properties', listProperties(trip), 'plate');
test('for...in also sees inherited ones', listByForIn(trip), 'plate,fare');
test('the inherited value is readable either way', trip.fare, 4500);
test('but it is not an own property', Object.hasOwn(trip, 'fare'), false);
test('while plate is', Object.hasOwn(trip, 'plate'), true);
test('number-like keys are sorted before string keys', Object.keys({ b: 1, 2: 2, a: 3, 1: 4 }), ['1', '2', 'b', 'a']);
Object.keys(obj).join(',') is the answer. The last assertion is the surprise worth carrying forward: object keys keep insertion order except for keys that look like array indexes, which are pulled to the front in numeric order. So { b: 1, 2: 2, a: 3, 1: 4 } enumerates as 1, 2, b, a. If order matters and your keys might be numeric, use a Map — it keeps strict insertion order for every key type.
Common mistakes
- Using
for...inand expecting only own keys. It also lists inherited enumerable keys. UseObject.keys, or check each key withObject.hasOwn. - Calling
join()with nothing in the brackets. It happens to use a comma, but the intent is hidden. Pass','so the reader sees it. - Assuming keys always keep insertion order. Number-like keys such as
1and2jump to the front.
Try it yourself
- Change
listPropertiesso the keys come out sorted alphabetically:name,rollno,sclass. - Make it print each key with its value, like
name=David Rayy. (Hint:Object.entries.) - Fix
listByForInso it skips inherited keys by checkingObject.hasOwn(obj, key)inside the loop.