Remap properties name and values using lodash

对着背影说爱祢 提交于 2019-11-30 14:46:52

Create a mapping of old and new keys, like this

var keyMapping = {'PropertyA': 'propertyA', ..., 'PropertyF': 'propertyNEW'}

and also a mapping of old and new values, like this

var valueMapping = {'Y': true, 'F': false}

And then using _.map and _.transform, you can transform the object, like this

var result = _.map(allItems, function(currentObject) {
    return _.transform(currentObject, function(result, value, key) {
        if (key === 'PropertyF' || key === 'PropertyG') {
            value = valueMapping(value);
        }
        result[keyMapping[key]] = value;
    });
});

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!