Map over object preserving keys

后端 未结 12 1453
再見小時候
再見小時候 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

提交回复
热议问题