map function for objects (instead of arrays)

前端 未结 30 2694
无人及你
无人及你 2020-11-22 04:23

I have an object:

myObject = { \'a\': 1, \'b\': 2, \'c\': 3 }

I am looking for a native method, similar to Array.prototype.map

30条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 05:06

    I came upon this as a first-item in a Google search trying to learn to do this, and thought I would share for other folsk finding this recently the solution I found, which uses the npm package immutable.

    I think its interesting to share because immutable uses the OP's EXACT situation in their own documentation - the following is not my own code but pulled from the current immutable-js documentation:

    const { Seq } = require('immutable')
    const myObject = { a: 1, b: 2, c: 3 }
    Seq(myObject).map(x => x * x).toObject();
    // { a: 1, b: 4, c: 9 } 
    

    Not that Seq has other properties ("Seq describes a lazy operation, allowing them to efficiently chain use of all the higher-order collection methods (such as map and filter) by not creating intermediate collections") and that some other immutable-js data structures might also do the job quite efficiently.

    Anyone using this method will of course have to npm install immutable and might want to read the docs:

    https://facebook.github.io/immutable-js/

提交回复
热议问题