+ 1
How can one change key names of a given object through a loop?
4 Respuestas
+ 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.
+ 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 }
+ 1
This code shows live the solution for change object‘s keys in a loop:
https://code.sololearn.com/W0Ci8ZxQ0ARK/?ref=app