Rename keys in an array of objects using JavaScript
I have an array of country objects. In this array I would like to replace the key name with country.
const countries = [ {"id": 1, "name": "Afghanistan"}, {"id": 2, "name": "Albania"}, {"id": 3, "name": "Algeria"}, {"id": 4, "name": "American Samoa"} ];
We can use map function to manipulate the array easily.
const transformed = countries.map(function(country) { country.country = country.name; delete country.name; return country; }) console.log(transformed); /* const countries = [ {"id": 1, "country": "Afghanistan"}, {"id": 2, "country": "Albania"}, {"id": 3, "country": "Algeria"}, {"id": 4, "country": "American Samoa"} ]; */