Convert an object to key-value pairs in JavaScript
Beginner · 3 min read
Arrays have lots of useful methods: map, filter, sort. Plain objects have almost none. The trick professionals use is to turn the object into an array of key-value pairs, use the array methods, and turn it back. That is how you uppercase every value, drop a field, or rename keys in one tidy line.
In this tutorial you will turn { a: 1, b: 2 } into [['a', 1], ['b', 2]] and back again. Then you will use that round trip to transform objects, and see the one thing it does not copy. You need to know objects, arrays and map.
What a pair is
A pair here is an array with exactly two items: the key, then the value. A list of pairs is an array of those small arrays:
const pairs = [['a', 1], ['b', 2]];
console.log(pairs[1][0], pairs[1][1]); // b 2
JavaScript calls these entries.
Unpacking a pair
When a function receives a pair, you can unpack it straight into two names with destructuring:
const show = ([key, value]) => `${key}=${value}`;
console.log(show(['a', 1])); // a=1
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
15 Convert an object to key/value pairs
easyTurn { a: 1, b: 2 } into [['a', 1], ['b', 2]], and turn it back again.
Stuck? Three hints, smallest first
- 1.
Object.entriesgoes one way,Object.fromEntriescomes back. - 2. The round trip is a shallow copy: nested objects are shared, not cloned.
- 3. A
Mapaccepts an entries array directly in its constructor.
Step 1: object to pairs
const student = { name: 'David Rayy', sclass: 'VI', rollno: 12 };
const toPairs = (obj) => Object.entries(obj);
console.log(toPairs({ a: 1, b: 2 })); // [ [ 'a', 1 ], [ 'b', 2 ] ]
console.log(toPairs({})); // []
Step 2: pairs back to an object
Object.fromEntries does the reverse:
const fromPairs = (pairs) => Object.fromEntries(pairs);
const back = fromPairs(toPairs(student));
console.log(back); // { name: 'David Rayy', sclass: 'VI', rollno: 12 }
console.log(back === student); // false
The result has the same keys and values, but it is a new object. That is why === says false: === on objects asks "is this the very same object?"
Step 3: transform the values
Now the useful part. Go to pairs, map each pair to a new pair, and come back:
const mapValues = (obj, fn) => fromPairs(toPairs(obj).map(([k, v]) => [k, fn(v)]));
console.log(mapValues({ a: 1, b: 2 }, (v) => v * 10)); // { a: 10, b: 20 }
console.log(mapValues({ a: 'x', b: 'y' }, (v) => v.toUpperCase())); // { a: 'X', b: 'Y' }
Each pair is unpacked into k and v, and a new pair [k, fn(v)] takes its place. The keys stay the same.
Step 4: filter the keys
The same pattern with filter drops pairs you don't want:
const filterKeys = (obj, keep) => fromPairs(toPairs(obj).filter(([k]) => keep(k)));
console.log(filterKeys(student, (k) => k !== 'rollno')); // { name: 'David Rayy', sclass: 'VI' }
[k] unpacks just the first item of each pair, since only the key matters here.
Step 5: pairs make a Map too
A Map is a key-value collection with its own methods. Its constructor accepts a list of pairs directly:
const asMap = new Map(toPairs(student));
console.log(asMap.get('rollno')); // 12
console.log([...asMap].length); // 3
Spreading a Map with [...asMap] gives the pairs back, in the same order.
Step 6: the round trip is shallow
Here is the catch. Copy an object that holds another object, and change the inner one in the copy:
const nested = { id: 1, seats: { total: 14, taken: 3 } };
const copy = fromPairs(toPairs(nested));
copy.seats.taken = 9;
console.log(nested.seats.taken); // 9
The original changed too. The round trip copies the top level only. Both objects point at the same seats object. This is called a shallow copy.
For a full, deep copy, use structuredClone, which copies every level:
const deep = structuredClone(nested);
deep.seats.taken = 1;
console.log(nested.seats.taken); // 9
Changing deep left nested alone.
Step 7: duplicate keys
If your pairs repeat a key, the last one wins:
console.log(fromPairs([['a', 1], ['a', 2]])); // { a: 2 }
The full solution
The panel converts the student to pairs and back, builds a Map, uppercases some values, and then proves the shallow-copy catch with the nested seats object. Press Run to see each result.
const student = { name: 'David Rayy', sclass: 'VI', rollno: 12 };
const toPairs = (obj) => Object.entries(obj);
const fromPairs = (pairs) => Object.fromEntries(pairs);
// Pairs are what make transforming an object convenient.
const mapValues = (obj, fn) => fromPairs(toPairs(obj).map(([k, v]) => [k, fn(v)]));
const filterKeys = (obj, keep) => fromPairs(toPairs(obj).filter(([k]) => keep(k)));
// The round trip is shallow: the nested object is the SAME object.
const nested = { id: 1, seats: { total: 14, taken: 3 } };
const copy = fromPairs(toPairs(nested));
copy.seats.taken = 9;
console.log('pairs :', toPairs(student));
console.log('back again :', fromPairs(toPairs(student)));
console.log('as a Map :', new Map(toPairs(student)));
console.log('uppercased :', mapValues({ a: 'x', b: 'y' }, (v) => v.toUpperCase()));
console.log('--- the round trip is shallow ---');
console.log('changed the copy, and the original says:', nested.seats.taken);
Output
13 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 13 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('entries produces pairs', toPairs({ a: 1, b: 2 }), [['a', 1], ['b', 2]]);
test('the round trip returns an equal object', fromPairs(toPairs(student)), student);
test('but not the same object', fromPairs(toPairs(student)) === student, false);
test('each pair has exactly two items', toPairs(student).every((p) => p.length === 2), true);
test('an empty object gives no pairs', toPairs({}), []);
test('and no pairs rebuild an empty object', fromPairs([]), {});
test('a Map can be built straight from the pairs', new Map(toPairs(student)).get('rollno'), 12);
test('and turned back into pairs', [...new Map(toPairs(student))], toPairs(student));
test('mapping the values keeps the keys', mapValues({ a: 1, b: 2 }, (v) => v * 10), { a: 10, b: 20 });
test('filtering the keys works too', filterKeys(student, (k) => k !== 'rollno'), { name: 'David Rayy', sclass: 'VI' });
test('the round trip is SHALLOW: the nested object is shared', nested.seats.taken, 9);
test('structuredClone makes a deep copy instead', (() => { const deep = structuredClone(nested); deep.seats.taken = 1; return nested.seats.taken; })(), 9);
test('a later duplicate key wins in fromEntries', fromPairs([['a', 1], ['a', 2]]), { a: 2 });
Object.entries and Object.fromEntries together are how you transform an object: convert to pairs, use the array methods you already know, convert back. mapValues above is four tokens of real work.
The shallow-copy assertion is the one to remember. fromEntries(entries(obj)) copies the top level only, so a nested object is shared between the original and the copy — changing copy.seats.taken changed nested.seats.taken too. structuredClone is the built-in deep copy, and the assertion shows it leaves the original alone.
Common mistakes
- Expecting a deep copy.
fromEntries(entries(obj))shares nested objects. UsestructuredClonefor a deep copy. - Returning a value instead of a pair from
map.map(([k, v]) => fn(v))loses the keys. Return[k, fn(v)]. - Comparing the copy with
===. It is a different object, so===isfalseeven when every value matches.
Try it yourself
- Use the pattern to add 10% to every price in
{ tea: 500, bread: 1200 }. - Rename every key to uppercase, so
{ a: 1 }becomes{ A: 1 }. - Keep only the entries whose value is a number.