admin管理员组文章数量:1392002
The following code populates an object called result
with the values in keys
as the keys and an empty string as each key's value. This is working as desired.
const keys = ['one', 'two', 'three'];
const result = {};
keys.forEach(key => {
result[key] = '';
});
console.log(result);
However, I'm wondering if the result
object can be created in a single mand by using .map
. Below is what I've tried but it yields an array of objects rather than a single object.
const result = keys.map(key => ({
[key]: ''
}));
console.log(result);
The following code populates an object called result
with the values in keys
as the keys and an empty string as each key's value. This is working as desired.
const keys = ['one', 'two', 'three'];
const result = {};
keys.forEach(key => {
result[key] = '';
});
console.log(result);
However, I'm wondering if the result
object can be created in a single mand by using .map
. Below is what I've tried but it yields an array of objects rather than a single object.
const result = keys.map(key => ({
[key]: ''
}));
console.log(result);
Share
Improve this question
asked Aug 18, 2021 at 20:28
knot22knot22
2,7785 gold badges35 silver badges61 bronze badges
1
-
1
.map()
always creates a new array that is in 1:1 relation with the old one. An array with X elements is definitely not the same as an object with X properties. You could still use.map()
but not as the sole thing to create the object. – VLAZ Commented Aug 18, 2021 at 20:32
4 Answers
Reset to default 8You can bine Object.fromEntries
and map
methods. With map
you can get array of [key, value]
pairs and then by calling fromEntries
you get an object from that array.
const keys = ['one', 'two', 'three'];
const result = Object.fromEntries(keys.map(k => ([k, ''])))
console.log(result)
Here's an alternative approach that only needs one method. (Array.prototype.reduce()
)
const keys = ["one", "two", "three"];
const result = keys.reduce((a, c) => ({ ...a, [c]: "" }), {});
console.log(result);
you can use your map, then reduce:
keys
.map(k => ({[k]: ""}))
.reduce((x, r) => ({...x, ...r}), {})
When you want to transform an array into another object, it is usefull to use reduce. I think this is more in line with your needs. The trick is when you iterate over the accumulator and you want to modify with an assignment, the assignment returns undefined. But you need to return an object. Undefined or the modified object is the modified object. And you can continue adding keys.
const keys = ['one', 'two', 'three'];
result = keys.reduce((obj, key) => (obj[key] = '') || obj, {});
console.log(result);
本文标签: javascriptmap equivalent of forEach to create an objectStack Overflow
版权声明:本文标题:javascript - .map equivalent of .forEach to create an object - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744743946a2622776.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论