Home > OS >  Swap key/value in object - JavaScript
Swap key/value in object - JavaScript

Time:09-10

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

CodePudding user response:

You might want to reconsider your data structure. It should be an array of objects.

eg: [{name:"Mohammad",age:"29"}, {name:"John",age:"19"}]

However, the code would look like

const swap = Object.entries(obj).reduce((accum, [key, value]) => ({...accum, ...{ [value]: key } }), {})

Why your code didn't work?

javascript computed properties

you tried with, newObj.obj[i] = i

instead it should be newObj[obj[i]] = i

You need to resolve the value for [obj[i]]

in this case, newObj[obj[i]] becomes 29. but newObj.obj becomes newObj.29 which'll be undefined at this point.

rewriting your function would look like,

/* {name:"Mohammad",age:"29"} ==>>  {Mohammad:"name",29:"age"} */

const obj = {name:"Mohammad",age:"29"}

function objValue (obj){
        const newObj = {}
    
    for (const [key, value] of Object.entries(obj)) {
     newObj[value] = key
    }
    
    return newObj
}

console.log(objValue(obj))

CodePudding user response:

You need to think about the logic first, If I needed to solve this I will make the object into two arrays and then convert them back to object by swapping there places like below:

const object = {
    name:"Mohammad",
    age:"29"
};

function swap(obj) {
    const key = Object.keys(obj);
    const value = Object.values(obj);
    let result = {};
    value.forEach((element, index) => {
        result[element] = key[index];
    });
    return result;
}

console.log(swap(object));

  • Related