最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript: replacing object keys with an array - Stack Overflow

programmeradmin0浏览0评论

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'}

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'}
Share Improve this question asked Aug 12, 2017 at 20:49 HannanHannan 1,1916 gold badges24 silver badges40 bronze badges 1
  • You'd need some kind of mapping; that you want to replace name with First Name and old with age, because property order ain't guaranteed. – Thomas Commented Aug 12, 2017 at 20:55
Add a ment  | 

7 Answers 7

Reset to default 4

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 pletely new object (with the new keys), assign the values to the new keys and then delete the old object.

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 can use Object.assign(), Object.entries(), .map(), spread element and puted 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);

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;

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);

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

It is suggested to make a deep copy of values of object if the values contains any other object

    let data = {'name': 'john', 'old': 18, 'place': 'USA'}
    let keys = ['firstName', 'age', 'country'] // 
    let values = Object.values(data)
    let newObject = {} 
    keys.forEach((element,index) => { newObject[element] = values[index] })
    console.log(newObject)

发布评论

评论列表(0)

  1. 暂无评论