Object.keys, values and entries
An object is easy to read by name and awkward to walk. The four static methods of Object close that gap: keys, values and entries turn the own properties into arrays, and fromEntries turns an array of pairs back into an object. With those four, every array method of the previous part works on an object.
This lesson covers the four, then Object.assign and the spread copy, which answer a different question: how to copy an object. Both copy one level, so the same nested object ends up under two names, which is the difference to keep in mind before the lesson on deep copies.
keys, values and entries
The three methods walk the own enumerable keys in the order the object keeps them, and each returns a new array. entries returns a pair per key, which is the shape that a destructuring pattern in a map takes apart, so the sum of all values is a reduce over the values. Inherited keys are not in any of the three arrays.
The file keys.mjs:
const scores = { ada: 36, grace: 40, alan: 41 };
console.log('the keys:', Object.keys(scores).join(','));
console.log('the values:', Object.values(scores).join(','));
console.log('the first pair:', JSON.stringify(Object.entries(scores)[0]));
console.log('all the pairs:', JSON.stringify(Object.entries(scores)));
const total = Object.values(scores).reduce((sum, score) => sum + score, 0);
console.log('the total:', total);
console.log('the number of entries:', Object.entries(scores).length);
const counts = { a: 1, 2: 2, b: 3 };
console.log('the order of mixed keys:', Object.keys(counts).join(','));
node keys.mjs
the keys: ada,grace,alan
the values: 36,40,41
the first pair: ["ada",36]
all the pairs: [["ada",36],["grace",40],["alan",41]]
the total: 117
the number of entries: 3
the order of mixed keys: 2,a,b
Three keys, three values and three pairs, in the same order, because all three methods read the same list. The total is the kind of report that used to need a for loop and now is one call, and the last line shows the order rule of the lesson on object keys: the key 2 is listed before the text keys.
fromEntries builds an object
Object.fromEntries takes any iterable of pairs and builds an object, so entries followed by a map or a filter and then fromEntries is the way to transform the values of an object without a loop. The pairs may be arrays or any iterable of two items, and the last pair for a key wins, as it does in an object literal.
The file fromentries.mjs:
const scores = { ada: 36, grace: 40, alan: 41 };
const doubled = Object.fromEntries(
Object.entries(scores).map(([name, score]) => [name, score * 2]),
);
console.log('doubled:', JSON.stringify(doubled));
const passed = Object.fromEntries(
Object.entries(scores).filter(([, score]) => score >= 40),
);
console.log('only forty and above:', JSON.stringify(passed));
const swapped = Object.fromEntries(
Object.entries(scores).map(([name, score]) => [score, name]),
);
console.log('keys and values swapped:', JSON.stringify(swapped));
const pairs = [['a', 1], ['b', 2]];
console.log('pairs to an object:', JSON.stringify(Object.fromEntries(pairs)));
console.log(
'a round trip keeps the order:',
Object.keys(Object.fromEntries(Object.entries(scores))).join(','),
);
node fromentries.mjs
doubled: {"ada":72,"grace":80,"alan":82}
only forty and above: {"grace":40,"alan":41}
keys and values swapped: {"36":"ada","40":"grace","41":"alan"}
pairs to an object: {"a":1,"b":2}
a round trip keeps the order: ada,grace,alan
The first two calls kept the shape of the object and changed the values, which is what a map and a filter do to an array. The third turned the values into keys, and the object obliged, because every key becomes text. The round trip at the end returns the same three names in the same order, so nothing is lost between the two forms.
Object.assign changes its target
Object.assign copies the own enumerable properties of every source into the first argument, which is the target, and returns that same target. It changes the object it is given rather than making a new one, and a later source wins over an earlier one. An empty object as the target is the old idiom for a copy, and the spread syntax of the lesson on copying does the same thing in one expression.
The file assign.mjs:
const target = { a: 1, b: 2 };
const first = { b: 20, c: 30 };
const result = Object.assign(target, first, { d: 40 });
console.log('the result is the target:', result === target);
console.log('the target was changed:', JSON.stringify(target));
console.log('the source was not:', JSON.stringify(first));
console.log('a later source wins:', target.b);
const copy = { ...target };
console.log('a spread copy has the same pairs:', JSON.stringify(copy));
console.log('but it is another object:', copy === target);
const fresh = Object.assign({}, { x: 1 }, { y: 2 });
console.log('an empty target is the copy idiom:', JSON.stringify(fresh));
console.log('a string source spreads its characters:', JSON.stringify(Object.assign({}, 'ab')));
node assign.mjs
the result is the target: true
the target was changed: {"a":1,"b":20,"c":30,"d":40}
the source was not: {"b":20,"c":30}
a later source wins: 20
a spread copy has the same pairs: {"a":1,"b":20,"c":30,"d":40}
but it is another object: false
an empty target is the copy idiom: {"x":1,"y":2}
a string source spreads its characters: {"0":"a","1":"b"}
The first line is the one to remember: the result is the target, not a copy of it, so a caller that keeps both names has one object. The sources were left alone, and the value from the later source won, which is the order the call documents. The last line is a detail worth knowing: a string is iterable, so a string source arrives as an object of character keys.
The copy is shallow
Both ways of copying read the top level and write the same values into a new object. A value that is itself an object is not copied: the new object holds the same reference, so a change through either name is visible through the other. Object.assign also reads a getter and stores its result as a plain value, which is a difference from the spread only when the source has accessors.
The file shallow.mjs:
const original = { name: 'Ada', address: { city: 'London' } };
const assigned = Object.assign({}, original);
const spread = { ...original };
assigned.address.city = 'Paris';
console.log('the assigned copy:', JSON.stringify(assigned));
console.log('the spread copy sees it:', JSON.stringify(spread));
console.log('the original sees it too:', JSON.stringify(original));
console.log('one nested object, three names:', assigned.address === original.address);
const measured = {
get size() {
return 'large';
},
};
const copiedGetter = Object.assign({}, measured);
console.log(
'assign turns a getter into a value:',
JSON.stringify(Object.getOwnPropertyDescriptor(copiedGetter, 'size')),
);
node shallow.mjs
the assigned copy: {"name":"Ada","address":{"city":"Paris"}}
the spread copy sees it: {"name":"Ada","address":{"city":"Paris"}}
the original sees it too: {"name":"Ada","address":{"city":"Paris"}}
one nested object, three names: true
assign turns a getter into a value: {"value":"large","writable":true,"enumerable":true,"configurable":true}
One write to a nested field changed all three reports, because there is one address object and three names for it. The last line shows the second property of a copy made with Object.assign: the getter was called once during the copy, and the result became an ordinary writable field. The spread does exactly the same, so neither call is a deep copy and structuredClone is the tool for the nested case.
Exercises
- Sort the entries of the scores object in keys.mjs by score and print the names. Which array method does the work, and where does fromEntries come in?
- Filter the entries of fromentries.mjs down to the names that are four letters long. How many pairs are left?
- Call Object.assign in assign.mjs with the empty object as the first source instead of the target. Which line of the output changes?
- Replace the spread in shallow.mjs with structuredClone and change the city again. Which of the three reports now keeps London?
- Read Object.keys of a string and of a number. What does each call return, and why?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
Object.entries({ a: 1 })return?Answer
An array with one pair, ["a", 1]
entries gives one two-item array per own enumerable key, and the key comes first.
-
What does
Object.assignreturn?Answer
The target object
The call writes into the first argument and returns that same object.
-
Which keys do Object.keys and Object.values read?
Answer
The own enumerable keys
The two methods list the contents of the object, so an inherited or hidden key is not in the list.
-
What kind of value does
Object.fromEntriestake?Answer
An iterable of pairs
It reads pair by pair and turns each pair into a key and a value.
-
What does this program print?
const o = { a: 1, b: 2 }; console.log(Object.values(o).join(","));Answer
1,2
values returns the values in key order, and join writes them with a comma.
-
What does this program print?
const o = Object.fromEntries([["a", 1], ["b", 2]]); console.log(JSON.stringify(o));Answer
{"a":1,"b":2}
Each pair became a field, and JSON writes the fields in insertion order.
-
What does this program print?
const target = { a: 1 }; const result = Object.assign(target, { a: 2 }); console.log(target.a, result === target);Answer
2 true
The source wins over the target and the call returns the target itself.
-
What does this program print?
const a = { n: { v: 1 } }; const b = { ...a }; b.n.v = 9; console.log(a.n.v);Answer
9
The spread copied the reference to the nested object, so both names reach the same field.
-
What does this program print?
const m = new Map([["a", 1]]); console.log(Object.keys(m).length);Answer
0
The entries of a Map are not properties of the object, so an object method finds no keys.
-
What does this program print?
const o = { a: 1 }; Object.assign(o, { a: 2 }, { a: 3 }); console.log(o.a);Answer
3
The sources are copied in order, so the last one to name a key sets its value.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev