在javascript中的map()中动态设置键?

rub*_*lex 7 javascript arrays associative-array

所以我知道如何动态设置密钥如下:

var hashObj = {};
hashObj[someValue] = otherValue;
Run Code Online (Sandbox Code Playgroud)

但我没有看到任何答案map():

var list = ['a', 'b', 'c'];

var hashObject = list.map(function(someValue) {
    return { someValue: 'blah' };
});

// should return: [ {'a': 'blah'}, {'b': 'blah'}, {'c': 'blah'} ];
Run Code Online (Sandbox Code Playgroud)

我知道我可以在for循环中这样做,但这在javascript使用中是不可能的map()吗?

Lim*_* H. 8

您需要将someValue其评估为其值.如果使用对象表示法,它将按字面解释为字符串.

您可以使用临时对象来实现您想要的:

var list = ['a', 'b', 'c'];

var hashObject = list.map(function(someValue) {
    var tmp = {};
    tmp[someValue] = 'blah';
    return tmp;
});
Run Code Online (Sandbox Code Playgroud)

  • ES6 简写:`return { [someValue]: 'blah' }` (2认同)

小智 5

我知道这确实是一个老问题,但答案对其他人可能有帮助。

正如已经说过的,Array.prototype.map用于获取新的array

但如果你想得到object而不是array- 也许你应该考虑使用Array.prototype.reducehttps://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce)?

const list = ['a', 'b', 'c'];

const hashObject = list.reduce((acc, current) => {
  acc[current] = 'blah';
  return acc;
}, {});

// hashObject equals: {"a":"blah","b":"blah","c":"blah"}
Run Code Online (Sandbox Code Playgroud)

如果您想获得与问题中提到的相同的结果,您Array.prototype.map当然可以使用:

const list = ['a', 'b', 'c'];

const hashObject = list.reduce((acc, current) => {
  acc[current] = 'blah';
  return acc;
}, {});

// hashObject equals: {"a":"blah","b":"blah","c":"blah"}
Run Code Online (Sandbox Code Playgroud)

您可以在 CodePen 上查看它的工作原理:https://codepen.io/grygork/pen/PojNrXO