Remap properties name and values using lodash

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

I have this array:

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


        
2条回答
  •  心在旅途
    2021-01-02 21:20

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

提交回复
热议问题