Map over object preserving keys

后端 未结 12 1418
再見小時候
再見小時候 2020-12-07 14:41

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

_.map({one:          


        
相关标签:
12条回答
  • 2020-12-07 15:05

    With Underscore

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

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

    DEMO


    With Lodash

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

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

    DEMO

    0 讨论(0)
  • 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>

    0 讨论(0)
  • 2020-12-07 15:07
    const mapObject = (obj = {}, mapper) =>
      Object.entries(obj).reduce(
        (acc, [key, val]) => ({ ...acc, [key]: mapper(val) }),
        {},
      );
    
    0 讨论(0)
  • 2020-12-07 15:09

    You can use _.mapValues(users, function(o) { return o.age; }); in Lodash and _.mapObject({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; }); in Underscore.

    Check out the cross-documentation here: http://jonathanpchen.com/underdash-api/#mapvalues-object-iteratee-identity

    0 讨论(0)
  • 2020-12-07 15:10

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

    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).

    0 讨论(0)
  • 2020-12-07 15:11

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

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

    jsbin

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

    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

    Since ES7 / ES2016 you can use Object.entries instead of Object.keys like this:

    let newObj = Object.assign(...Object.entries(obj).map([k, v] => ({[k]: v * 3})));
    
    0 讨论(0)
提交回复
热议问题