【问题标题】:Set key dynamically inside map() in javascript?在javascript中的map()内动态设置键?
【发布时间】:2015-07-24 05:00:08
【问题描述】:

所以我知道如何像这样动态设置密钥:

var hashObj = {};
hashObj[someValue] = otherValue;

但是我没有看到任何关于map()的答案:

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

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

// should return: [ {'a': 'blah'}, {'b': 'blah'}, {'c': 'blah'} ];

我知道我可以在 for 循环等中执行此操作,但是在仅使用 map() 的 JavaScript 中这是不可能的吗?

【问题讨论】:

    标签: javascript arrays associative-array


    【解决方案1】:

    我知道这是一个很老的问题,但回答可能对其他人有帮助。

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

    但如果您想获得object 而不是array - 也许您应该考虑使用Array.prototype.reduce (https://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"}
    

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

    const list = ['a', 'b', 'c'];
    
    const hashArrayOfObjects = list.map((current) => {
      return {[current]: 'blah'};
    });
    
    // hashArrayOfObjects equals: [{"a":"blah"},{"b":"blah"},{"c":"blah"}]
    

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

    【讨论】:

      【解决方案2】:

      通常使用 'map()' 方法从每个返回值中获取新数组。 在您的情况下,我建议使用 forEach()。

      var list = ['a','b','c'];
      var hashObject = {};
      list.forEach( function( key ) {
          hashObject[ key ] = 'blah';
      });
      

      或者使用underscore.js库的object()

      var list = ['a','b','c'];
      var hashObject = _.object( list ); // { a: undefined, b: undefined, c: undefined }
      hashObject = _.mapObject( hashObject, function( val, key ) {
          return 'blah';
      });
      

      再一次,Array.prototype.map 仅用于获取新的“数组”而不是“对象”。

      【讨论】:

        【解决方案3】:

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

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

        var list = ['a', 'b', 'c'];
        
        var hashObject = list.map(function(someValue) {
            var tmp = {};
            tmp[someValue] = 'blah';
            return tmp;
        });
        

        【讨论】:

        • 是的,您不能创建使用变量名称作为属性名称的 JS 文字对象定义。因此,您必须声明一个对象,然后像此答案一样单独分配属性(使用变量中的属性名称)。
        • ES6 简写:return { [someValue]: 'blah' }
        猜你喜欢
        • 2011-07-24
        • 2012-10-25
        • 2018-08-18
        • 2022-06-15
        • 2013-01-25
        • 2013-10-03
        • 1970-01-01
        • 2019-01-11
        • 2019-12-23
        相关资源
        最近更新 更多