Map - a data structure of the other interchangeable

Map into an array

the Map the myMap new new = const () 
  .set (to true,. 7) 
  .set ({foo:. 3}, [ 'ABC']); [... the myMap] // Extended operator ( ) 
// [[to true, 7], [{foo: 3 }, [ 'abc']]]
...

Array into Map  

new Map([
  [true, 7],
  [{foo: 3}, ['abc']]
])
// Map {
//   true => 7,
//   Object {foo: 3} => ['abc']
// }

Map into objects  

function strMapToObj (strMap) { 
  the let the Object.create obj = (null); 
  for (the let [K, V] of strMap) { 
    obj [K] = V; 
  } 
  return obj; 
} 

const the myMap the Map = new new () 
  .set ( 'Yes', to true) 
  .set ( 'NO', to false); strMapToObj (the myMap) 
// {Yes: to true, NO:} to false if there is a non-string keys, then the key name may be translated into strings and then as an object keys

 Objects into Map 

let obj = {"a":1, "b":2};
let map = new Map(Object.entries(obj));
function objToStrMap(obj) {
  let strMap = new Map();
  for (let k of Object.keys(obj)) {
    strMap.set(k, obj[k]);
  }
  return strMap;
}

objToStrMap({yes: true, no: false})
// Map {"yes" => true, "no" => false}

Map into JSON  

 

Map key names are strings, then you can select an object into JSON. 
strMapToJson function (strMap) { 
  return the JSON.stringify (strMapToObj (strMap)); 
} 

the let the myMap the Map = new new () SET ( 'Yes', to true) .set ( 'NO', to false);. 
strMapToJson (the myMap) 
// '{ "yes": true, "no": false}'

 

Map of non-string keys, then you can choose into an array of JSON.

mapToArrayJson function (Map) { 
  return the JSON.stringify ([Map ...]); 
} 

the let the myMap the Map = new new () SET (to true,. 7) .set ({foo:. 3}, [ 'ABC']).; 
mapToArrayJson (the myMap) 
// '[[to true,. 7], [{ "foo":. 3}, [ "ABC"]]]'

JSON into Map 

function jsonToStrMap(jsonStr) {
  return objToStrMap(JSON.parse(jsonStr));
}

jsonToStrMap('{"yes": true, "no": false}')
// Map {'yes' => true, 'no' => false}

  

 

Guess you like

Origin www.cnblogs.com/blogZhao/p/12564215.html