Map.keys() returns a MapIterator object which can be converted to Array using Array.from:
let keys = Array.from( myMap.keys() );
// ["a", "b"]
EDIT: you can also convert iterable object to array using spread syntax
let keys =[ ...myMap.keys() ];
// ["a", "b"]
Answer from pawel on Stack OverflowVideos
Map.keys() returns a MapIterator object which can be converted to Array using Array.from:
let keys = Array.from( myMap.keys() );
// ["a", "b"]
EDIT: you can also convert iterable object to array using spread syntax
let keys =[ ...myMap.keys() ];
// ["a", "b"]
You can use the spread operator to convert Map.keys() iterator in an Array.
let myMap = new Map().set('a', 1).set('b', 2).set(983, true)
let keys = [...myMap.keys()]
console.log(keys)
This is not a Map object. It's just a regular object. So, use Object.entries and then use map on the key value pair:
const map = {"a": 1, "b": 2, "c": 3};
const mapped = Object.entries(map).map(([k,v]) => `${k}_${v}`);
console.log(mapped);
Object.entries returns:
[["a",1],["b",2],["c",3]]
Then loop through each of those inner arrays and create the string using template literals
If you have a Map object, use Array.from(map) to get the entries of the map and use the second parameter of Array.from to go over each entry and create the desired string
Array.from(map, ([k,v]) => `${k}_${v}`)
It's not a map, it's an object. (You might consider using a Map, though.)
To get its properties as key/value pairs, you can use Object.entries, which you can then apply map to:
map = Object.entries(map).map(([key, value]) => key + "_" + value);
Object.entries is relatively new, but easily polyfilled for older environments.
Live Example:
var map = {"a": 1, "b": 2, "c": 3};
map = Object.entries(map).map(([key, value]) => key + "_" + value);
console.log(map);
Or, using a Map, you can use its built-in entries method, which returns an iterable, passing it into Array.from and using Array.from's mapping callback:
var map = new Map([
["a", 1],
["b", 2],
["c", 3]
]);
map = Array.from(map.entries(), ([key, value]) => key + "_" + value);
console.log(map);
(Or expand the iterable into an array — [...map.entries()] — and use map on it, but the above avoids a temporary throw-away array.)
In both cases, I'm using destructuring in the parameter list of the arrow function, which receives an array in [key, value] format.
Map.keys() returns an iterator you can spread the iterator using spread syntax
const map = new Map();
map.set(0, 'Zero');
map.set(1, 'One');
map.set(2, 'Two');
[...map.keys()].forEach(key => {
console.log(key);
})
It's Array.prototype.map actually, it's defined for arrays, so use Array.from to convert the keys to an array and then use map:
const map = new Map();
map.set(0, 'Zero');
map.set(1, 'One');
map.set(2, 'Two');
console.log(...Array.from(map.keys()).map(key => {
return key ** 2; // square the keys
}));
You can use a for..of loop to loop directly over the map.entries and get the keys.
function getByValue(map, searchValue) {
for (let [key, value] of map.entries()) {
if (value === searchValue)
return key;
}
}
let people = new Map();
people.set('1', 'jhon');
people.set('2', 'jasmein');
people.set('3', 'abdo');
console.log(getByValue(people, 'jhon'))
console.log(getByValue(people, 'abdo'))
You could convert it to an array of entries (using [...people.entries()]) and search for it within that array.
let people = new Map();
people.set('1', 'jhon');
people.set('2', 'jasmein');
people.set('3', 'abdo');
let jhonKeys = [...people.entries()]
.filter(({ 1: v }) => v === 'jhon')
.map(([k]) => k);
console.log(jhonKeys); // if empty, no key found otherwise all found keys.
There is one more which seems to be the fastest:
for (let [key, value] of map.entries()) {
sum+=value
}
JSBench with the methods as per the following. These are the results from fastest to slowest:
Map.prototype.forEach()for ofloop throughMap.prototype.keys()for ofloop throughMap.prototype[Symbol.iterator]()- Create array from
Map.prototype.keys()and thenArray.prototype.forEach()
There is no native map to the Object object, but how about this:
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
Object.keys(myObject).forEach(function(key, index) {
myObject[key] *= 2;
});
console.log(myObject);
// => { 'a': 2, 'b': 4, 'c': 6 }
But you could easily iterate over an object using for ... in:
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
for (var key in myObject) {
if (myObject.hasOwnProperty(key)) {
myObject[key] *= 2;
}
}
console.log(myObject);
// { 'a': 2, 'b': 4, 'c': 6 }
Update
A lot of people are mentioning that the previous methods do not return a new object, but rather operate on the object itself. For that matter I wanted to add another solution that returns a new object and leaves the original object as it is:
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
// returns a new object with the values at each key mapped using mapFn(value)
function objectMap(object, mapFn) {
return Object.keys(object).reduce(function(result, key) {
result[key] = mapFn(object[key])
return result
}, {})
}
var newObject = objectMap(myObject, function(value) {
return value * 2
})
console.log(newObject);
// => { 'a': 2, 'b': 4, 'c': 6 }
console.log(myObject);
// => { 'a': 1, 'b': 2, 'c': 3 }
Array.prototype.reduce reduces an array to a single value by somewhat merging the previous value with the current. The chain is initialized by an empty object {}. On every iteration a new key of myObject is added with twice the key as the value.
Update
With new ES6 features, there is a more elegant way to express objectMap.
const objectMap = (obj, fn) =>
Object.fromEntries(
Object.entries(obj).map(
([k, v], i) => [k, fn(v, k, i)]
)
)
const myObject = { a: 1, b: 2, c: 3 }
console.log(objectMap(myObject, v => 2 * v))
How about a one-liner in JS ES10 / ES2019 ?
Making use of Object.entries() and Object.fromEntries():
let newObj = Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, v * v]));
The same thing written as a function:
function objMap(obj, func) {
return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, func(v)]));
}
// To square each value you can call it like this:
let mappedObj = objMap(obj, (x) => x * x);
This function uses recursion to square nested objects as well:
function objMap(obj, func) {
return Object.fromEntries(
Object.entries(obj).map(([k, v]) =>
[k, v === Object(v) ? objMap(v, func) : func(v)]
)
);
}
// To square each value you can call it like this:
let mappedObj = objMap(obj, (x) => x * x);
With ES7 / ES2016 you can't use Objects.fromEntries, but you can achieve the same using Object.assign in combination with spread operators and computed key names syntax:
let newObj = Object.assign({}, ...Object.entries(obj).map(([k, v]) => ({[k]: v * v})));
ES6 / ES2015 Doesn't allow Object.entries, but you could use Object.keys instead:
let newObj = Object.assign({}, ...Object.keys(obj).map(k => ({[k]: obj[k] * obj[k]})));
ES6 also introduced for...of loops, which allow a more imperative style:
let newObj = {}
for (let [k, v] of Object.entries(obj)) {
newObj[k] = v * v;
}
array.reduce()
Instead of Object.fromEntries and Object.assign you can also use reduce for this:
let newObj = Object.entries(obj).reduce((p, [k, v]) => ({ ...p, [k]: v * v }), {});
Inherited properties and the prototype chain:
In some rare situation you may need to map a class-like object which holds properties of an inherited object on its prototype-chain. In such cases Object.keys() and Object.entries() won't work, because these functions do not include the prototype chain.
If you need to map inherited properties, you can use for (key in myObj) {...}.
Here is an example of such situation:
const obj1 = { 'a': 1, 'b': 2, 'c': 3}
const obj2 = Object.create(obj1); // One of multiple ways to inherit an object in JS.
// Here you see how the properties of obj1 sit on the 'prototype' of obj2
console.log(obj2) // Prints: obj2.__proto__ = { 'a': 1, 'b': 2, 'c': 3}
console.log(Object.keys(obj2)); // Prints: an empty Array.
console.log(Object.entries(obj2)); // Prints: an empty Array.
for (let key in obj2) {
console.log(key); // Prints: 'a', 'b', 'c'
}
However, please do me a favor and avoid inheritance. :-)