使用 Lodash 重命名 array/object 中的几个键

Renaming several keys in an array/object with Lodash

我如何使用 Lodash 从 x 到 y?

var x = [
    {id: 22, location: 'Vienna'},
    {id: 13, location: 'London'},
    {id: 21, location: 'Paris'}
];


var y = [
    {value: 22, name: 'Vienna'},
    {value: 13, name: 'London'},
    {value: 21, name: 'Paris'}
];

这是代码

var x = [
    {id: 22, location: 'Vienna'},
    {id: 13, location: 'London'},
    {id: 21, location: 'Paris'}
];

var keyMap = {
  id: 'value',
  location: 'name'
};

var y = x.map(function(obj) {
  return _.mapKeys(obj, function(value, key) {
    return keyMap[key];
  });
});

document.querySelector('#result').innerHTML = JSON.stringify(y, undefined, 2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.5.1/lodash.min.js"></script>
<pre id="result"></pre>

请注意,如果您不需要触摸某些键,此实现可能会有用:

var y = x.map(function(obj) {
  return _.mapKeys(obj, function(value, key) {
    if(key in keyMap){
      return keyMap[key];
    } else {
      return key;
    }
  });
});