0

I have a Map that is set up like this

const directory = new Map()
.set('John', { age:25, gender: 'M'} )
.set('Mary', { age:51, gender: 'M'} ) 
.set('Sam', { age:15, gender: 'M', id: 322 } )
.set('Jane', { age:15, gender: 'M', paid: true } );

I wish to transform this to an array of jsons with a new property "name" for each of the key from the map:

[
  { "name": "John", "age":25, "gender": "M" },
  { "name": "Mary", "age":51, "gender": "F" },  
  { "name": "Sam", "age":15, "gender": "M", "id": 322 },  
  { "name": "Jane", "age":19, "gender": "F", "paid": true }
]

I tried JSON.stringify([...directory]) and bunch of other stuff but the not sure of any efficient way of including the key as part of the json.

razshan
  • 1,128
  • 12
  • 41
  • 59
  • 1
    I'm going to go out on a limb here and assume by "array of jsons" you mean "array of objects." JSON is a *textual notation* for data exchange. [(More here.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. – T.J. Crowder Sep 18 '17 at 16:34
  • 1
    What have you tried? What has your research turned up? What part are you stuck on? – T.J. Crowder Sep 18 '17 at 16:35

2 Answers2

2

As you already used the spread property to destructure the Map, you then just need to map that 2d array to an array of objects, which can be easily done with array destructuring:

 [...directory].map(([name,obj]) => ({name,...obj}));

or without ESnext:

[...directory].map(([name,obj]) => Object.assign({name},obj));

Try it

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 1
    Quite so, no reason not to use spread instead of `Array.from`. As you say, spread *properties* (lurkers: the second use of `...`) are only Stage 3, so they'll probably (but only probably) make ES2018 -- but they're well-supported by transpilers. – T.J. Crowder Sep 18 '17 at 16:41
  • I don't normally upvote when there's **no** explanation, though. (Did this time.) – T.J. Crowder Sep 18 '17 at 16:43
0

You could use Array.from and build the wanted objects.

const directory = new Map()
        .set('John', { age: 25, gender: 'M' })
        .set('Mary', { age: 51, gender: 'M' }) 
        .set('Sam', { age: 15, gender: 'M', id: 322 })
        .set('Jane', { age: 15, gender: 'M', paid: true }),
    result = Array.from(directory, ([name, o]) => Object.assign({ name }, o));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392