Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

105
Views
Swap object values for few properties in javascript

current object

const obj = {
  k1: v1,
  k2: v2,
  x1: v3,
  x2: v4,
  y: {
    z1: v5,
    z2: v6
  }
}

expected object

const obj = {
  k1: v2,
  k2: v1,
  x1: v4,
  x2: v3,
  y: {
    z1: v6,
    z2: v5
  }
}

Have tried individual swap method for each key and also tried below object assign way

const obj = {
  k1: 'v1',
  k2: 'v2',
  x1: 'v3',
  x2: 'v4',
  y: {
    z1: 'v5',
    z2: 'v6'
  }
}
Object.assign(obj, {
  k1: obj.k2,
  k2: obj.k1,
  x1: obj.x2,
  x2: obj.x1,
  y: {
    z1: obj.y.z2,
    z2: obj.y.z1,
  }
});

Object.keys(obj).forEach(
  (k) =>
    obj[k] === null ||
    (obj[k] === undefined && delete obj[k])
);

console.log(obj)

for some cases once object assign is executed undefined will come for x1 or x2 key because v3 or v4 are not mandatory. so after converting trying to remove the undefined keys from object

Expecting a optimized and better solution for it

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Your solution was accession undefined keys from obj such as obj.k4 and obj.k3 also they were assigning to wrong keys aswell k3 and k4.

Your Corrected Solution

const obj = {
  k1: 'v1',
  k2: 'v2',
  x1: 'v3',
  x2: 'v4',
  y: {
    z1: 'v5',
    z2: 'v6'
  }
};
Object.assign(obj, {
  k1: obj.k2,
  k2: obj.k1,
  x1: obj.x2,
  x2: obj.x1,
  y: {
    z1: obj.y.z2,
    z2: obj.y.z1,
  }
});
console.log(obj);

You can also make use of spread operator for achieving the same.

let obj = {
  k1: 'v1',
  k2: 'v2',
  x1: 'v3',
  x2: 'v4',
  y: {
    z1: 'v5',
    z2: 'v6'
  }
};
obj = {...obj, ...{
  k1: obj.k2,
  k2: obj.k1,
  x1: obj.x2,
  x2: obj.x1,
  y: {
    z1: obj.y.z2,
    z2: obj.y.z1,
  }
}}
console.log(obj);

about 4 years ago · Juan Pablo Isaza Report

0

You can write a method to remove the undefined:

const clean = o => JSON.parse(JSON.stringify(o))
  
const obj = {
  k1: 'v1',
  k2: 'v2',
  x1: 'v3',
  x2: 'v4',
  y: {
    z1: 'v5',
    z2: 'v6',
  },
}

Object.assign(obj, {
  k1: obj.k2,
  k2: obj.k1,
  k3: obj.k4,
  k4: obj.k3,
  y: {
    z1: obj.v6,
    z2: obj.v5,
  },
})

console.log('obj:', obj)
console.log('clean object:', clean(obj))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!