While working with javascript objects and arrays, the generic requirement developers encounter is converting an object to an array of key-value pairs. This article demonstrates easy ways to convert objects to an array of key-value pairs in javascript using different methods and example illustrations.
Table of Contents:
- Convert an Object{} to an Array[] of Key-Value Pairs in Javascript using Object.keys()
- Convert an Object{} to an Array[] of Key-Value Pairs in Javascript using Object.entries()
Convert an Object{} to an Array[] of Key-Value Pairs in Javascript using Object.keys()
Javascript’s Object.keys() returns an array of enumerable property names of the object.
Example 1:-
Convert the object { personFirstName: ‘George’, personLastName: ‘Smith’, dateOfBirth: “Nov 14 1984”, age: 37} to an array of key-value pairs
Code:-
let myObject = { personFirstName: 'George', personLastName: 'Smith', dateOfBirth: "Nov 14 1984", age: 37}; var key_value_pair = Object.keys(myObject).map((key) => [key, myObject[key]]); console.log(key_value_pair);
Output:-
Frequently Asked:
[ [ 'personFirstName', 'George' ], [ 'personLastName', 'Smith' ], [ 'dateOfBirth', 'Nov 14 1984' ], [ 'age', 37 ] ]
Example 2:-
Convert the object {1: ‘George’, 2: ‘Will’, 3: ‘Patrick’, 4: ‘Barbara’} to an array of key-value pairs
Code:-
let myObject = { 1: 'George', 2: 'Will', 3: 'Patrick', 4: 'Barbara'}; var key_value_pair = Object.keys(myObject).map((key) => [key, myObject[key]]); console.log(key_value_pair);
Output:-
[ [ '1', 'George' ], [ '2', 'Will' ], [ '3', 'Patrick' ], [ '4', 'Barbara' ] ]
Convert an Object{} to an Array[] of Key-Value Pairs in Javascript using Object.entries()
Javascript’s Object.entries() returns an array of enumerable key-value pairs of the object.
Example 1:-
Convert the object { personFirstName: ‘George’, personLastName: ‘Smith’, dateOfBirth: “Nov 14 1984”, age: 37} to an array of key-value pairs
Code:-
let myObject = { personFirstName: 'George', personLastName: 'Smith', dateOfBirth: "Nov 14 1984", age: 37}; var key_value_pair = Object.entries(myObject); console.log(key_value_pair);
Output:-
[ [ 'personFirstName', 'George' ], [ 'personLastName', 'Smith' ], [ 'dateOfBirth', 'Nov 14 1984' ], [ 'age', 37 ] ]
Example 2:-
Convert the object {1: ‘George’, 2: ‘Will’, 3: ‘Patrick’, 4: ‘Barbara’} to an array of key-value pairs
Code:-
let myObject = { 1: 'George', 2: 'Will', 3: 'Patrick', 4: 'Barbara'}; var key_value_pair = Object.entries(myObject); console.log(key_value_pair);
Output:-
[ [ '1', 'George' ], [ '2', 'Will' ], [ '3', 'Patrick' ], [ '4', 'Barbara' ] ]
I hope this article helped you to convert an object to an array of key-value pairs in javascript. Good Luck !!!