Remap properties name and values using lodash

前端 未结 2 1952
刺人心
刺人心 2021-01-02 20:57

I have this array:

aItems = [{
    \"PropertyA\": \"apple\",
    \"PropertyB\": \"banana\",
    \"PropertyC\": \"dog\",
    \"PropertyD\": \"hotdog\",
    \"         


        
2条回答
  •  孤街浪徒
    2021-01-02 21:33

    Yes, since lodash v3.8.0 you can remap objects in any way desireable

    ES5 code

    var items = [ { oldKey: 'oldValue' /*...*/ } ]
    
    var keyMapping = { oldKey: 'newKey' /*...*/ }
    var valueMapping = { oldValue: 'newValue' /*...*/ }
    
    var remapper = function(item){
      return _(item) // lodash chain start
        .mapKeys( function(v, k){ return keyMapping[k] } )
        .mapValues( function(v){ return valueMapping[v] } )
        .value() // lodash chain end
    }
    
    var remappedItems = items.map(remapper)
    

    ES2015/ES6 code

    let items = [ { oldKey: 'oldValue' /*...*/ } ]
    
    let keyMapping = { oldKey: 'newKey' /*...*/ }
    let valueMapping = { oldValue: 'newValue' /*...*/ }
    
    let remapper = item => _(item) // lodash chain start
      .mapKeys( (v, k)=> keyMapping[k] )
      .mapValues( v => valueMapping[v] )
      .value() // lodash chain end
    
    let remappedItems = items.map(remapper)
    

提交回复
热议问题