简体   繁体   English

将es6映射的内容转换为JSON数组

[英]Convert es6 map's content to an array of JSON

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”的json数组,以用于地图中的每个键:

[
  { "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. 我尝试了JSON.stringify([... directory])和其他很多东西,但是不确定是否有将密钥作为json的一部分的有效方法。

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: 由于您已经使用了spread属性来分解地图,因此您只需要将该2d数组映射到对象数组即可,这可以通过数组解构轻松实现:

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

or without ESnext: 或不带ESnext:

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

Try it 试试吧

You could use Array.from and build the wanted objects. 您可以使用Array.from并构建所需的对象。

 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; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM