【问题标题】:Trying to swap key value pairs of an object. Any advices?试图交换对象的键值对。有什么建议吗?
【发布时间】:2021-11-04 18:37:20
【问题描述】:

试图交换对象的键值对!

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

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

【问题讨论】:

标签: javascript object iteration key-value swap


【解决方案1】:

逻辑上最直接的解决方案:

  • 使用 Object.entries 将对象转换为条目数组 ([[key1, val1], [key2, val2], ...])
  • 使用 map 交换每个条目 ([[val1, key1], [val2, key2], ...])
  • 使用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]。条件是避免在转换为字符串时键和值相等的情况下完全删除条目。)

【讨论】:

    【解决方案2】:

    您可以创建新对象:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-25
      • 2011-08-06
      • 2010-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多