Is there any way to rename js object keys using underscore.js

后端 未结 13 1844
小蘑菇
小蘑菇 2020-12-05 01:21

I need to convert a js object to another object for passing onto a server post where the names of the keys differ for example

var a = {
    name : \"Foo\",
          


        
13条回答
  •  天涯浪人
    2020-12-05 02:17

    It's been solved here https://stackoverflow.com/a/30940370/1360897

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

提交回复
热议问题