+ 1

How can one change key names of a given object through a loop?

28th Oct 2020, 3:07 PM
asɥɐ🔹ʞɐɹnnƃı
asɥɐ🔹ʞɐɹnnƃı - avatar
4 odpowiedzi
+ 3
Thanks maf and JaScript
2nd Nov 2020, 10:17 PM
asɥɐ🔹ʞɐɹnnƃı
asɥɐ🔹ʞɐɹnnƃı - avatar
+ 2
let obj = { name: "john" } let keys = Object.keys(obj) // returns an array with just keys or the obj. keys.forEach(key => { let value = obj[key] // stored the value of current key so that i can delete it now. delete obj[key] // its deleted, now assign the value to a new key obj.fullname = value }) console.log(obj); // { fullname: "john" } The problem here is that it would rename all the keys to fullname, which you don't want. To solve that, create a new array which contains the new keys (lets call it keysArr), and inside the keys.forEach you can get a second parameter with key, which is the index. keys.forEach((key, i) => ... Now instead of obj.fullname = value, use obj[keysArr[i]] = value There might be another way, but i know this one.
28th Oct 2020, 3:40 PM
maf
maf - avatar
+ 2
asɥɐ🔹ʞɐɹnnƃı read this after uve read the other answer: So after fixing the problem, this would be our new code. let obj = { name: "john", age: 6 } let keys = Object.keys(obj) /* Object.keys(obj) returns an array with current keys or the obj. */ let keysArr = ["fullname", "height"] /* your new keys */ keys.forEach((key, index) => { let value = obj[key] /* stored the value of current key so that i can delete the key now. */ delete obj[key] /* its deleted, now assign the current value to a new key which we would get from the keysArr which contains our new keys. */ obj [ keysArr [ index ] ] = value /* explanation of this line: the current index, suppose it is 0 (beginner), keysArr [ 0 ] would be "fullname" and obj [ "fullname" ] is what we are assigning the value to. */ }) console.log(obj); // { fullname: "John", height: 6 }
28th Oct 2020, 3:51 PM
maf
maf - avatar
+ 1
This code shows live the solution for change object‘s keys in a loop: https://code.sololearn.com/W0Ci8ZxQ0ARK/?ref=app
28th Oct 2020, 4:29 PM
JaScript
JaScript - avatar