映射对象保留键

问题描述 投票:122回答:10

如果使用javascript对象调用,则underscore.js中的map函数返回从对象的值映射的值数组。

_.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });
=> [3, 6, 9]

有没有办法让它保存钥匙?即,我想要一个返回的函数

{one: 3, two: 6, three: 9}
javascript underscore.js lodash
10个回答
208
投票

使用Underscore

Underscore提供了一个函数_.mapObject来映射值并保留键。

_.mapObject({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; });

// => { one: 3, two: 6, three: 9 }

DEMO


随着Lodash

Lodash提供了一个函数_.mapValues来映射值并保留键。

_.mapValues({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; });

// => { one: 3, two: 6, three: 9 }

DEMO


0
投票

您可以在Lodash中使用_.mapValues(users, function(o) { return o.age; });,在Underscore中使用_.mapObject({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; });

查看这里的交叉文档:http://jonathanpchen.com/underdash-api/#mapvalues-object-iteratee-identity


56
投票

我设法在lodash中找到了所需的函数,这是一个类似于下划线的实用程序库。

http://lodash.com/docs#mapValues

_.mapValues(object, [callback=identity], [thisArg])

使用与通过回调运行对象的每个自己的可枚举属性而生成的对象和值相同的键创建对象。回调绑定到thisArg并使用三个参数调用; (价值,关键,对象)。


19
投票

var mapped = _.reduce({ one: 1, two: 2, three: 3 }, function(obj, val, key) {
    obj[key] = val*3;
    return obj;
}, {});

console.log(mapped);
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>

13
投票

我知道这是旧的,但现在Underscore有一个新的对象地图:

_.mapObject(object, iteratee, [context]) 

您当然可以为阵列和对象构建灵活的映射

_.fmap = function(arrayOrObject, fn, context){
    if(this.isArray(arrayOrObject))
      return _.map(arrayOrObject, fn, context);
    else
      return _.mapObject(arrayOrObject, fn, context);
}

9
投票

普通JS(ES6 / ES2015)中的这个版本怎么样?

let newObj = Object.assign(...Object.keys(obj).map(k => ({[k]: obj[k] * 3})));

jsbin

如果要以递归方式映射对象(映射嵌套的obj),可以这样做:

const mapObjRecursive = (obj) => {
  Object.keys(obj).forEach(key => {
    if (typeof obj[key] === 'object') obj[key] = mapObjRecursive(obj[key]);
    else obj[key] = obj[key] * 3;
  });
  return obj;
};

jsbin

从ES7 / ES2016开始,您可以使用Object.entries代替Object.keys,如下所示:

let newObj = Object.assign(...Object.entries(obj).map([k, v] => ({[k]: v * 3})));

3
投票

_.map返回一个数组,而不是一个对象。

如果你想要一个物体,你最好使用不同的功能,比如each;如果你真的想使用地图你可以做这样的事情:

Object.keys(object).map(function(value, index) {
   object[value] *= 3;
})

但这很令人困惑,当看到map时,人们会期望得到一个数组作为结果,然后用它做点什么。


2
投票

我想你想要一个mapValues函数(将函数映射到一个对象的值),这很容易实现自己:

mapValues = function(obj, f) {
  var k, result, v;
  result = {};
  for (k in obj) {
    v = obj[k];
    result[k] = f(v);
  }
  return result;
};

2
投票

我知道它已经很长时间了,但是仍然是最明显的折叠解决方案(也就是js中的reduce),为了完整起见,我会留在这里:

function mapO(f, o) {
  return Object.keys(o).reduce((acc, key) => {
    acc[key] = f(o[key])
    return acc
  }, {})
}

1
投票

下划线地图错误的混合修复:P

_.mixin({ 
    mapobj : function( obj, iteratee, context ) {
        if (obj == null) return [];
        iteratee = _.iteratee(iteratee, context);
        var keys = obj.length !== +obj.length && _.keys(obj),
            length = (keys || obj).length,
            results = {},
            currentKey;
        for (var index = 0; index < length; index++) {
          currentKey = keys ? keys[index] : index;
          results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
        }
        if ( _.isObject( obj ) ) {
            return _.object( results ) ;
        } 
        return results;
    }
}); 

一个简单的解决方法,保持正确的键并作为对象返回它仍然使用与客户端相同的方式,您可以使用此函数来覆盖bugy _.map函数

或者仅仅因为我用它作为mixin

_.mapobj ( options , function( val, key, list ) 
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.