javascript 映射对象保留键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19023226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:06:13  来源:igfitidea点击:

Map over object preserving keys

javascriptunderscore.jslodash

提问by xuanji

The mapfunction in underscore.js, if called with a javascript object, returns an array of values mapped from the object's values.

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

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

is there a way to make it preserve the keys? ie, I want a function that returns

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

{one: 3, two: 6, three: 9}

回答by GG.

With Underscore

下划线

Underscore provides a function _.mapObjectto map the values and preserve the keys.

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

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

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

DEMO

DEMO



With Lodash

洛达什

Lodash provides a function _.mapValuesto map the values and preserve the keys.

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

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

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

DEMO

DEMO

回答by xuanji

I managed to find the required function in lodash, a utility library similar to underscore.

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

http://lodash.com/docs#mapValues

http://lodash.com/docs#mapValues

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

Creates an object with the same keys as object and values generated by running each own enumerable property of object through the callback. The callback is bound to thisArg and invoked with three arguments; (value, key, object).

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

创建一个具有与对象相同的键和值的对象,这些值是通过回调运行对象的每个可枚举属性而生成的。回调绑定到 thisArg 并使用三个参数调用;(值、键、对象)。

回答by kunalgolani

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>

回答by Rayjax

I know this is old, but now Underscore has a new map for objects :

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

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

You can of course build a flexible map for both arrays and objects

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

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

回答by Rotareti

How about this version in plain JS (ES6 / ES2015)?

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

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

jsbin

jsbin

If you want to map over an object recursively(map nested obj), it can be done like this:

如果要递归映射对象(映射嵌套 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

jsbin

Since ES7 / ES2016you can use Object.entriesinstead of Object.keyslike this:

ES7 / ES2016 开始,您可以使用Object.entries而不是Object.keys这样:

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

回答by Darwin

I know it's been a long time, but still the most obvious solution via fold (aka reduce in js) is missing, for the sake of completeness i'll leave it here:

我知道这已经很长时间了,但仍然缺少通过 fold(在 js 中也称为 reduce)的最明显的解决方案,为了完整起见,我将其留在这里:

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

回答by Alberto Zaccagni

_.mapreturns an Array, not an Object.

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

If you want an object you're better off using a different function, like each; if you really want to use map you could do something like this:

如果你想要一个对象,你最好使用不同的函数,比如each; 如果你真的想使用地图,你可以做这样的事情:

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

but that is confusing, when seeing mapone would expect to have an array as result and then make something with it.

但这令人困惑,当看到map一个人会期望有一个数组作为结果然后用它做一些事情时。

回答by joyrexus

I think you want a mapValuesfunction (to map a function over the values of an object), which is easy enough to implement yourself:

我认为您需要一个mapValues函数(将函数映射到对象的值上),这很容易实现自己:

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

回答by Nigel Kirby

const mapObject = (obj = {}, mapper) =>
  Object.entries(obj).reduce(
    (acc, [key, val]) => ({ ...acc, [key]: mapper(val) }),
    {},
  );

回答by Pascal

A mix fixfor the underscore map bug:P

下划线映射错误的混合修复: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;
    }
}); 

A simple workaround that keeps the right key and return as object It is still used the same way as i guest you could used this function to override the bugy _.map function

一个简单的解决方法,保留正确的键并作为对象返回它仍然使用与我来宾相同的方式,您可以使用此函数来覆盖有问题的 _.map 函数

or simply as me used it as a mixin

或者只是像我一样将它用作 mixin

_.mapobj ( options , function( val, key, list )