0

Trying to swap key-value pairs of an object!

// an object through we have to iterate and swap the key value pairs
const product = {
  id: "FRT34495",
  price: 34.56,
  nr: 34456,
};
//  A function that actually swap them, but don't delete old properties
const change = () => {
  for (let key in product) {
    const x = key;
    key = product[key];
    product[key] = x;
  }
    return product;
};

console.log(change());

//
{
  '34456': 'nr',
  id: 'FRT34495',
  price: 34.56,
  nr: 34456,
  FRT34495: 'id',
  '34.56': 'price'
}

the problem is that I need the object with key-value pairs swapped, but in the same amount, not twice more as we can see above, I need to delete the old ones. Any advice guys?

rigan
  • 27
  • 4
  • Does this answer your question? [Swap key with value in object](https://stackoverflow.com/questions/23013573/swap-key-with-value-in-object) – pilchard Sep 07 '21 at 23:32

3 Answers3

3

Most logically straight-forwarding solution:

  • Turn object into entries array ([[key1, val1], [key2, val2], ...]) using Object.entries
  • Swap each of the entries ([[val1, key1], [val2, key2], ...]) using map
  • Turn back into object using Object.fromEntries
function swapKV (obj) {
  const entries = Object.entries(obj)
  const swappedEntries = entries.map([k, v] => [v, k])
  const swappedObj = Object.fromEntries(swappedEntries)
  return swappedObj
}

...or more concise:

const swapKV = obj => Object.fromEntries(Object.entries(obj).map([k, v] => [v, k]))

(Of course, another solution would be to just add if (String(x) !== String(key)) delete product[x] to your code. The condition is there to avoid deleting the entry altogether in case key and value are equal when converted to a string.)

CherryDT
  • 20,425
  • 2
  • 39
  • 63
0

You can create new object:

const product = {
  id: "FRT34495",
  price: 34.56,
  nr: 34456,
};

const change = (obj) => {
  let result = {}
  for (let key in obj) {
    result[obj[key]] = key
  }
    return result;
};

console.log(change(product));
Nikola Pavicevic
  • 13,800
  • 6
  • 18
  • 38
0

This may help!

const swapKV = (obj) => {
  const newObj = {};

  for (let val in obj) {
     newObj[obj[val]] = val;
  }

  return newObj;
}
vanntile
  • 2,693
  • 4
  • 28
  • 46
Adam Foody
  • 19
  • 3