How to Convert a Plain Object into an Es6 Map

How to convert a plain object into an ES6 Map?

Yes, the Map constructor takes an array of key-value pairs.

Object.entries is a new Object static method available in ES2017 (19.1.2.5).

const map = new Map(Object.entries({foo: 'bar'}));

map.get('foo'); // 'bar'

It's currently implemented in Firefox 46+ and Edge 14+ and newer versions of Chrome

If you need to support older environments and transpilation is not an option for you, use a polyfill, such as the one recommended by georg:

Object.entries = typeof Object.entries === 'function' ? Object.entries : obj => Object.keys(obj).map(k => [k, obj[k]]);

How to get Map as an object in javascript ES6?

Better way to convert map to object

let jsonResponse = {};
for(let [key,val] of MapObject.entries()){
jsonResponse[key]= val;
}

console.log(jsonResponse);

How to convert Map to array of object?

You could take Array.from and map the key/value pairs.

let map = new Map().set('a', 1).set('b', 2),    array = Array.from(map, ([name, value]) => ({ name, value }));
console.log(array);

Convert Map to JavaScript object

You could loop over the map and over the keys and assign the value

function createPaths(aliases, propName, path) {    aliases.set(propName, path);}
var map = new Map(), object = {};
createPaths(map, 'paths.aliases.server.entry', 'src/test');createPaths(map, 'paths.aliases.dist.entry', 'dist/test');
map.forEach((value, key) => { var keys = key.split('.'), last = keys.pop(); keys.reduce((r, a) => r[a] = r[a] || {}, object)[last] = value;});
console.log(object);

When would you use an ES6 Map over an Object?

MDN lists a number of important differences:

  • An Object has a prototype, so there are default keys in the map. [editor: the good old hasOwnProperty issue]
  • The keys of an Object are Strings, where they can be any value for a Map.
  • You can get the size of a Map easily while you have to manually keep track of size for an Object.
  • A Map iterates its elements in insertion order, whereas iteration order is not specified for Objects.

So a Map is finally an insert-ordered key-value store for Javascript, which additionally allows mapping any value to any value, instead of restricting keys to be strings. This can greatly simplify some code where ordering is important, or where objects or other complex data types need to be associated with other data.

How do you JSON.stringify an ES6 Map?

Both JSON.stringify and JSON.parse support a second argument. replacer and reviver respectively. With replacer and reviver below it's possible to add support for native Map object, including deeply nested values

function replacer(key, value) {
if(value instanceof Map) {
return {
dataType: 'Map',
value: Array.from(value.entries()), // or with spread: value: [...value]
};
} else {
return value;
}
}
function reviver(key, value) {
if(typeof value === 'object' && value !== null) {
if (value.dataType === 'Map') {
return new Map(value.value);
}
}
return value;
}

Usage:

const originalValue = new Map([['a', 1]]);
const str = JSON.stringify(originalValue, replacer);
const newValue = JSON.parse(str, reviver);
console.log(originalValue, newValue);

Deep nesting with combination of Arrays, Objects and Maps

const originalValue = [
new Map([['a', {
b: {
c: new Map([['d', 'text']])
}
}]])
];
const str = JSON.stringify(originalValue, replacer);
const newValue = JSON.parse(str, reviver);
console.log(originalValue, newValue);

Convert a result of type Object into a Mapstring, string[] in Angular

Here is a wroker function you can use:

function buildMap(obj: any) {
let map = new Map();
Object.keys(obj).forEach(key => {
map.set(key, obj[key]);
});
return map;
}

For more options please see answers in this SO: How to convert a plain object into an ES6 Map?

Enjoy!

Trying to map through document.getgetElementsByTagName in reactjs

You can try something like this:

function App() {
const [h2, setH2] = useState([]);

const getH2 = () => {
const elements = [];
const el = document.getElementsByTagName('h2');
for (const item of el) {
elements.push(item.innerText);
}
setH2(elements);
};
return (
<div>
<h2>One</h2>
<h2>Two</h2>
<h2>Three</h2>
<h2>Four</h2>

<hr />
<button onClick={getH2}>Get Innner Text</button>
<hr />
<ul>
{h2.map((item, i) => (
<li key={i}>{item}</li>
))}
</ul>
</div>
);
}

Live Demo: https://stackblitz.com/edit/react-vtb3fv



Related Topics



Leave a reply



Submit