'Trying to swap key value pairs of an object. Any advices?
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?
Solution 1:[1]
Most logically straight-forwarding solution:
- Turn object into entries array (
[[key1, val1], [key2, val2], ...]
) usingObject.entries
- Swap each of the entries (
[[val1, key1], [val2, key2], ...]
) usingmap
- 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.)
Solution 2:[2]
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));
Solution 3:[3]
This may help!
const swapKV = (obj) => {
const newObj = {};
for (let val in obj) {
newObj[obj[val]] = val;
}
return newObj;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | vanntile |