[英]How to parse a javascript map into an array using ES6
I need to parse a JS map, converting it into an array, with the following form:我需要解析一个JS map,将其转换为数组,格式如下:
[
{
name: "21 years old",
totalUsers: 2,
},
...
]
So, if for example I have this map:所以,例如,如果我有这个 map:
const ages = {
"21": 2,
"18": 10,
}
The method "parseAges" has to return:方法“parseAges”必须返回:
[
{
name: "21 years old",
totalUsers: 2,
},
{
name: "18 years old",
totalUsers: 10,
},
]
This is the way I am doing it using for...of (ES2017):这就是我使用 for...of (ES2017) 的方式:
const ages = {
"21": 2,
"18": 10,
}
function parseAges() {
const agesArr = [];
for (const [key, value] of Object.entries(ages)) {
agesArr.push({
name: `${key} years old`,
totalUsers: value
})
}
return agesArr;
}
console.log(parseAges());
How can I do it without the for...of, in ES6?在 ES6 中没有 for...of 怎么办?
This is the way I am doing it using for...of (ES2017):
这就是我使用 for...of (ES2017) 的方式:
for/of is part of ES6 ( ES2015 ). for/of是 ES6 ( ES2015 ) 的一部分。
How can I do it without the for...of, in ES6?
在 ES6 中没有 for...of 怎么办?
There was no particular syntax added in ES6, other than for/of, that would make this easier than using a newer or older syntax.除了 for/of 之外,ES6 中没有添加任何特定语法,这比使用新旧语法更容易。
Object.entries
is one alternative ( ES2017 ): Object.entries
是一种替代方案( ES2017 ):
const list = Object.entries(ages).map(([age, users]) => ({
name: `${age} years old`,
totalUsers: users,
}));
Object.keys
is another alternative (ES5/ ES2009 ): Object.keys
是另一种选择(ES5/ ES2009 ):
const list = Object.keys(ages).map((age) => ({
name: `${age} years old`,
totalUsers: ages[age],
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.