0

试图交换对象的键值对!

// 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'
}

问题是我需要交换键值对的对象,但数量相同,而不是我们在上面看到的两倍,我需要删除旧的。有什么建议吗?

4

2 回答 2

3

最符合逻辑的直接解决方案:

  • 使用将对象转换为条目数组 ( [[key1, val1], [key2, val2], ...])Object.entries
  • 使用交换每个条目 ( [[val1, key1], [val2, key2], ...])map
  • 使用转回对象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
}

...或更简洁:

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

(当然,另一种解决方案是只添加if (String(x) !== String(key)) delete product[x]到您的代码中。条件是避免在转换为字符串时键和值相等的情况下完全删除条目。)

于 2021-09-07T23:21:52.947 回答
0

您可以创建新对象:

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

于 2021-09-07T23:27:12.033 回答