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
Add a ment  | 

4 Answers 4

Reset to default 8

You 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