使用lodash重新映射属性名称和值

时间:2015-06-19 14:02:11

标签: javascript underscore.js lodash

我有这个数组:

aItems = [{
    "PropertyA": "apple",
    "PropertyB": "banana",
    "PropertyC": "dog",
    "PropertyD": "hotdog",
    "PropertyE": "coldcat",
    "PropertyF": "Y",
    "PropertyG": "N"
},
...,
{
    "PropertyA": "this",
    "PropertyB": "is",
    "PropertyC": "json",
    "PropertyD": "code",
    "PropertyE": "wow",
    "PropertyF": "N",
    "PropertyG": "N"
}]

我想使用 lodash 来获得此结果:

aItems = [{
    "propertyA": "apple",
    "propertyB": "banana",
    "propertyC": "dog",
    "propertyD": "hotdog",
    "propertyE": "coldcat",
    "propertyNEW": true,
    "propertyG": false
},
...,
{
    "propertyA": "this",
    "propertyB": "is",
    "propertyC": "json",
    "propertyD": "code",
    "propertyE": "wow",
    "propertyNEW": false,
    "propertyG": false
}]

我希望将每个属性名称与其他名称一起映射,并更改某些特定属性的值。 我可以使用 lodash 吗?

2 个答案:

答案 0 :(得分:10)

是的,因为lodash v3.8.0你可以用任何想要的方式重新映射对象

ES5代码

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代码

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)

答案 1 :(得分:4)

创建旧键和新键的映射,例如

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

以及旧值和新值的映射,例如

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

然后使用_.map_.transform,您可以转换对象,就像这样

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;
    });
});