I'm new to JS and experimenting the things. I have following object:
var data = {'name': 'john', 'old': 18, 'place': 'USA'}
How can I switch the keys of this object with the following array?
var array = ['First Name', 'age', 'country']
To look following:
{'First Name': 'john', 'age': 18, 'country': 'USA'}
The only way to rename a key of an object is to assign the value of the old key to the new key and then delete the old key
Object[ new_key ] = Object[ old_key ];
delete Object[ old_key ];
Another way is to create a completely new object (with the new keys), assign the values to the new keys and then delete the old object.
You can use Object.assign()
, Object.entries()
, .map()
, spread element and computed properties to assign the property name to a new object having value to to current index of property, value within iteration, set identifier for original object to result of Object.assign()
call
let array = ['First Name', 'age', 'country'] let data = {'name': 'john', 'old': 18, 'place': 'USA'} data = Object.assign({}, ...Object.entries(data) .map(([, prop], index) => ({[array[index]]: prop}))); console.log(data);
var array = ['First Name', 'age', 'country']; var data = {'name': 'john', 'old': 18, 'place': 'USA'}; var keys = Object.keys(data); var newData = {}; for (var a in array) { //using new obj newData[array[a]] = data[keys[a]]; //editing same obj data[array[a]] = data[keys[a]]; delete data[keys[a]]; } console.log(data); console.log(newData);
var array = ['First Name', 'age', 'country']; var list = [ { 'name': 'john 1', 'old': 18, 'place': 'USA' }, { 'name': 'john 2', 'old': 19, 'place': 'USB' }, { 'name': 'john 3', 'old': 20, 'place': 'USC' }, ]; var newList = []; for (var item in list) { var newData = {}; for (var a in array) { newData[array[a]] = list[item][Object.keys(list[item])[a]]; } newList.push(newData); } console.log(newList);
You could use an object with the replacement keys and iterate it for changing the keys.
var data = { name: 'john', old: 18, place: 'USA' }, newKeys = { name: 'First Name', old: 'age', place: 'country' }; Object.keys(newKeys).forEach(function (k) { data[newKeys[k]] = data[k]; delete data[k]; }); console.log(data);
Rather than switching
the object keys; which cannot be done and you'd have to delete keys and add the new one, you could simply create a new object with the desired keys:
var data2 = {};
data2['First Name'] = data.name;
data2.age = data.old;
data2country = data.place;
var data = {'name': 'john', 'old': 18, 'place': 'USA'}
var ary = ['First Name', 'age', 'country']
// create key-value pairs array
var obj_entries = Object.entries(data)
var new_data =ary.reduce((acc, value, idx)=>{
acc[value]=obj_entries[idx][1];
return acc;
}, {})
console.log(new_data)
Maybe a functional approach
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.