How to use my object like an array using map function in JavaScript?

JavaScript objects aren't arrays, so they don't have array methods like map(). However, you can use Object.keys(), Object.values(), or Object.entries() to convert object data into arrays, then apply map().

Using Object.keys() with map()

Extract object keys as an array, then use map() to iterate:

const object = {
    name: 'John',
    age: 21,
    countryName: 'US',
    subjectName: 'JavaScript'
};

const allKeys = Object.keys(object);
console.log("All keys:", allKeys);

// Using map to get values from keys
const mappedValues = allKeys.map(key => object[key]);
console.log("Mapped values:", mappedValues);
All keys: [ 'name', 'age', 'countryName', 'subjectName' ]
Mapped values: [ 'John', 21, 'US', 'JavaScript' ]

Using Object.values() with map()

Extract object values directly and transform them:

const object = {
    name: 'John',
    age: 21,
    countryName: 'US',
    subjectName: 'JavaScript'
};

const allValues = Object.values(object);
console.log("All values:", allValues);

// Transform values using map
const uppercaseValues = allValues.map(value => String(value).toUpperCase());
console.log("Uppercase values:", uppercaseValues);
All values: [ 'John', 21, 'US', 'JavaScript' ]
Uppercase values: [ 'JOHN', '21', 'US', 'JAVASCRIPT' ]

Using Object.entries() with map()

Get key-value pairs as arrays and transform them:

const object = {
    name: 'John',
    age: 21,
    countryName: 'US',
    subjectName: 'JavaScript'
};

const entries = Object.entries(object);
console.log("Entries:", entries);

// Transform entries using map
const formatted = entries.map(([key, value]) => `${key}: ${value}`);
console.log("Formatted:", formatted);
Entries: [ [ 'name', 'John' ], [ 'age', 21 ], [ 'countryName', 'US' ], [ 'subjectName', 'JavaScript' ] ]
Formatted: [ 'name: John', 'age: 21', 'countryName: US', 'subjectName: JavaScript' ]

Comparison of Methods

Method Returns Use Case
Object.keys() Array of property names When you need to work with property names
Object.values() Array of property values When you only need the values
Object.entries() Array of [key, value] pairs When you need both keys and values

Conclusion

Use Object.keys(), Object.values(), or Object.entries() to convert object data into arrays, then apply map(). Choose the method based on whether you need keys, values, or both.

Updated on: 2026-03-15T23:18:59+05:30

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements