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'}
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. Commented Aug 12, 2017 at 20:55

7 Answers 7

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

Sign up to request clarification or add additional context in comments.

1 Comment

but you said "How can I switch the keys of this object with the following array?", why so this is the best answer?
1

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

2 Comments

Thats a brilliant answer. I ended up using the method with new obj. Just a quick question, do the new keys will maintain the same index as the old ones? What if I want to try this method on hundreds of items? Thanks a lot
I added an example with a list
1

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

1 Comment

for me this is the best answer
1

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;

Comments

1

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

2 Comments

@Laurianti, you need some kind of relation. objects have no order and you can not rely on the order of the keys,
if you use Object.keys(newKeys) yes, if you use Object.keys(data) you have to save it first you change it
0
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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.