使用Lodash重命名数组/对象中的几个键

时间:2016-02-28 22:05:37

标签: json key rename 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'}
];

1 个答案:

答案 0 :(得分:4)

这是代码



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>
&#13;
&#13;
&#13;