'Renaming several keys in an array/object with Lodash
How can I get from x to y with Lodash?
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'}
];
Solution 1:[1]
Here is the code
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>
Solution 2:[2]
Note that if you need to not touch some keys, this implementation might be useful :
var y = x.map(function(obj) {
return _.mapKeys(obj, function(value, key) {
if(key in keyMap){
return keyMap[key];
} else {
return key;
}
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | satish |
Solution 2 | ZettaP |