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
  • 85
  • 7
  • 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
  • 25,571
  • 5
  • 49
  • 74
0

This may help!

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

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

  return newObj;
}
vanntile
  • 2,727
  • 4
  • 26
  • 48
Adam Foody
  • 19
  • 3
0

You can also try this:

const swap = (obj) => {
return Object.fromEntries(
Object.entries(obj)
  .map((key) => key.reverse())`.concat(Object.entries(obj))`
  );
 };

If the original object is to be also added to the output, concat can be used. The user asks for a function which also keeps the old properties. Otherwise no need.

yilmaz85
  • 1
  • 3
  • 1
    Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/349538) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you’ve made. – jasie Jul 19 '22 at 06:10