In JavaScript, when you work with Objects, it is obvious to perform a map function for objects by iterating through objects to manipulate data.
JavaScript objects does not have a native map() function but you can use ES feature Object.fromEntries() & Object.entries()
to perform map operation of iterating over the objects.
Using ES10 Object.fromEntries() and Object.entries() approach (Quick Solution)
In ES10, Object.fromEntries
method was introduced, and it helps to transform a list of key-value pair to Object.
The Object.entries()
method returns array of given objects based on its [key, value]
pairs.
To achieve map function for objects using Object.fromEntries() and Object.entries() follow the below process,
- Use
Object.entries()
to convert the JavaScript object to an array of objects, and then you can iterate the array using the arraymap()
function to map function for objects. - Later use
Object.fromEntries()
to transform the list of [key, value] pairs to Object.
Code
const cinemas = {
"exitDoors": 3,
"seats": 200,
"speakers": 10,
"ticketCounters": 2
}
const objectEntryFn = (obj) => Object.fromEntries(Object.entries(obj).map(([key, val]) => [key, val * 2]));
console.log(objectEntryFn(cinemas));
Output
{
exitDoors: 6,
seats: 400,
speakers: 20,
ticketCounters: 4
}
In the above example, the JavaScript Object(cinemas
) is iterated and manipulated to produce a new result double its current value.
- To achieve the double of its current value, the above JavaScript object is passed to the function
objectEntryFn()
, it usesObject.entries(obj)
to convert the object to[key, value]
pairs. - Map function(
.map()
) is used to iterate through the [key,value] pairs to manipulate(double) the value using[key, val * 2]
. - At last
Object.fromEntries()
is used to transform the [key, value] pairs back to JavaScript Object.
Using ES7 Object.assign() and Object.entries() approach
Another similar approach to above approach is to use Object.assign()
method instead of Object.fromEntries()
method.
Object.assign() copies all its enumerable properties from source to target object and returns the modified target object.
The Object.entries()
method returns an array of given objects based on its [key, value]
pairs.
Code
const cinemas = {
"exitDoors": 3,
"speakers": 10,
"seats": 200,
"ticketCounters": 2
}
let objectAssignFn = (obj) => Object.assign({}, ...Object.entries(obj).map(([key, val]) => ({
[key]: val * 2
})));
console.log(objectAssignFn(cinemas));
Output
{
exitDoors: 6,
seats: 400,
speakers: 20,
ticketCounters: 4
}
In the above example, the JavaScript object is converted to [key, value] pairs using Object.entries()
and iterated using the .map()
to manipulates its value(doubled the value)Object.assign()
is used to copy all the updated [key, value] pairs to another object and return it.
Using ES6 Object.assign() and Object.keys() approach
The Object.keys()
method returns the array of keys of the given object.
You can use Object.keys()
to iterate over the JavaScript Object and use the map function to manipulate the value.
Use Object.assign()
to copy the properties from source to target object and perform map function for objects.
Code
const cinemas = {
"seats": 200,
"speakers": 10,
"exitDoors": 3,
"ticketCounters": 2
}
let objectAssignKeyFn = (obj) => Object.assign({}, ...Object.keys(obj).map(key => ({
[key]: obj[key] * 2
})));
console.log(objectAssignKeyFn(cinemas));
Output
{
seats: 400,
speakers: 20,
exitDoors: 6,
ticketCounters: 4
}
In the above example, the JavaScript object is converted to an array of keys pairs using Object.keys()
and iterated using the .map()
to manipulate its value(doubled the value)Object.assign()
is used to copy all the updated [key, value] pairs to another object and return it.
Using reduce()
The reduce()
method executes a callback function on each element of an array in order, passing the return value from the calculation on the preceding element.
You can use Object.keys()
to iterate over the JavaScript Object and use the map function to manipulate the value using the reduce
method.
By the above process, the reduce()
method helps map the objects’ function.
Code
const cinemas = {
"exitDoors": 3,
"speakers": 10,
"seats": 200,
"ticketCounters": 2
}
const reduceFn = (obj, mapFn) => Object.keys(obj).reduce((result, key) => {
result[key] = mapFn(obj)[key] * 2;
return result;
}, {});
console.log(reduceFn(cinemas, (value) => value));
Output
{
exitDoors: 6,
speakers: 20,
seats: 400,
ticketCounters: 4
}
The Object.keys()
is used to create a list of keys to iterate through the reduce()
method.
The reduce function accepts the callback function and executes the callback function on each array element.
It takes the specific key value from the mapFn() obj and double it using mapFn(obj)[key] * 2
and return the result.
Using For Each
The forEach()
method executes provided function once on every element in array.
Here, Object.keys()
method is used to extract the JavaScript object keys to iterate over the object and manipulate using the .forEach()
function.
Code
const cinemas = {
"exitDoors": 3,
"seats": 200,
"speakers": 10,
"ticketCounters": 2,
"name":"TechMam"
}
Object.keys(cinemas).forEach(function(key, index) {
if (cinemas.hasOwnProperty(key) && !isNaN(cinemas[key])) {
cinemas[key] *= 2;
}
});
console.log(cinemas);
Output
{
exitDoors: 6,
name: "TechMam",
seats: 400,
speakers: 20,
ticketCounters: 4
}
In the above example, .hasOwnProperty(key)
is used to check for the key in the Object(cinemas) and !isNaN(cinemas[key])
is used to check for number value.
This will only update if the key is present and the value is a number.
Using For…of
The for...of
is used to iterate over the iterable objects like string, array.
This is also similar to the forEach
way of mapping function for objects.
Code
const cinemas = {
"seats": 200,
"exitDoors": 3,
"speakers": 10,
"ticketCounters": 2
}
let newCinemasSpec = {}
for (let [k, v] of Object.entries(cinemas)) {
newCinemasSpec[k] = v * 2;
}
console.log(newCinemasSpec);
Output
{
seats: 400,
exitDoors: 6,
speakers: 20,
ticketCounters: 4
}
Using map()
The map()
method iterates over each element and returns a new array populated with results of calling provided function.
Code
var names = [{
"firstName": "Sam",
"lastName": "Brook"
},
{
"firstName": "Brad",
"lastName": "Matt"
}, {
"firstName": "Charle",
"lastName": "Bezos"
}
]
var fullNames = names.map((key, v) => {
return key.firstName + " " + key.lastName;
});
console.log(fullNames);
Output
["Sam Brook", "Brad Matt", "Charle Bezos"]
Note: It is always fair to use Object.map
instead of Object.prototype.map
.