返回介绍

solution / 2800-2899 / 2822.Inversion of Object / README_EN

发布于 2024-06-17 01:02:59 字数 3312 浏览 0 评论 0 收藏 0

2822. Inversion of Object

中文文档

Description

Given an object or an array obj, return an inverted object or array invertedObj.

The invertedObj should have the keys of obj as values and the values of obj as keys. The indices of array should be treated as keys. It is guaranteed that the values in obj are only strings. The function should handle duplicates, meaning that if there are multiple keys in obj with the same value, the invertedObj should map the value to an array containing all corresponding keys.

 

Example 1:

Input: obj = {"a": "1", "b": "2", "c": "3", "d": "4"}
Output: invertedObj = {"1": "a", "2": "b", "3": "c", "4": "d"}
Explanation: The keys from obj become the values in invertedObj, and the values from obj become the keys in invertedObj.

Example 2:

Input: obj = {"a": "1", "b": "2", "c": "2", "d": "4"}
Output: invertedObj = {"1": "a", "2": ["b", "c"], "4": "d"}
Explanation: There are two keys in obj with the same value, the invertedObj mapped the value to an array containing all corresponding keys.

Example 3:

Input: obj = ["1", "2", "3", "4"]
Output: invertedObj = {"1": "0", "2": "1", "3": "2", "4": "3"}
Explanation: Arrays are also objects therefore array has changed to an object and the keys (indices) from obj become the values in invertedObj, and the values from obj become the keys in invertedObj.

 

Constraints:

  • obj is a valid JSON object or array
  • typeof obj[key] === "string"
  • 2 <= JSON.stringify(obj).length <= 105

Solutions

Solution 1

function invertObject(obj: Record<any, any>): Record<any, any> {
  const ans: Record<any, any> = {};
  for (const key in obj) {
    if (ans.hasOwnProperty(obj[key])) {
      if (Array.isArray(ans[obj[key]])) {
        ans[obj[key]].push(key);
      } else {
        ans[obj[key]] = [ans[obj[key]], key];
      }
    } else {
      ans[obj[key]] = key;
    }
  }
  return ans;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文