I want swap key(s) in an object with value(s) and swap value(s) with key(s)
{name:"Mohammad",age:"29"} ==>> {Mohammad:"name",29:"age"}
Below code work:
function swap(oldObj) {
let newObj = {};
for (let i in oldObj) {
newObj[oldObj[i]] = i;
}
return newObj;
}
since below code log values(s) in an object:
Actually obj[i] is object's value(S)
function objValue (obj){
for (let i in obj){
console.log(obj[i]);
}
}
I changed swap function (first block code) to:
function swap(oldObj) {
let newObj = {};
for (let i in oldObj) {
newObj.oldObj[i] = i;
}
return newObj;
}
Actually I try call oldObj's value(s) with oldObj[i] and add this as key to newObj with newObj.oldObj[i] instead of newObj[oldObj[i]]
but error occur
Uncaught TypeError TypeError: Cannot set properties of undefined (setting 'name')
newObj.oldObj[i] = i<- this line won't work. Your first versionnewObj[oldObj[i]] = iis correct. I don't understand what are you asking about. Your first version code works as you want, Isn't your problem solved already?newObj.oldObj[i]means, first read the key named "oldObj" fromnewObj, let's name the valuetemp, then read the key that is stored in variableifromtemp.newObj["oldObj"][i]