如何使用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'}
];
答案 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;