JavaScript Compact Object All In One

xgqfrms發表於2024-05-18

JavaScript Compact Object All In One

LeetCode 2705. Compact Object

solutions

function compactObject(obj: Obj): Obj {
  let temp;
  if(Array.isArray(obj)) {
    obj = obj.filter(i => Boolean(i));
    // obj = obj.filter(i => !!Boolean(i)); ✅
    // obj = obj.filter(i => Boolean(i) !== false); ✅
    temp = [];
  } else {
    temp = {};
  }
  for(let key in obj) {
    if(Boolean(obj[key]) !== false) {
      // if(Object.prototype.toString.call(obj[key]).includes(`object`)) { ❌ bug
      if(Array.isArray(obj[key]) || Object.prototype.toString.call(obj[key]) === `[object Object]`) {
        temp[key] = compactObject(obj[key]);
      } else {
        temp[key] = obj[key];
      }
    }
  }
  return temp;
};


image

https://leetcode.com/problems/compact-object/?envType=study-plan-v2&envId=30-days-of-javascript

demos

type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };
type Obj = Record<string, JSONValue> | Array<JSONValue>;

function compactObject(obj: Obj): Obj {
  let temp;
  if(Array.isArray(obj)) {
    obj = obj.filter(i => Boolean(i));
    temp = [];
  } else {
    temp = {};
  }
  for(let key in obj) {
    if(Boolean(obj[key]) !== false) {
      // if(Object.prototype.toString.call(obj[key]).includes(`object`)) { ❌ bug
      if(Array.isArray(obj[key]) || Object.prototype.toString.call(obj[key]) === `[object Object]`) {
        temp[key] = compactObject(obj[key]);
      } else {
        temp[key] = obj[key];
      }
    }
  }
  return temp;
};

// function compactObject(obj: Obj): Obj {
//   let temp;
//   if(Array.isArray(obj)) {
//     obj = obj.filter(i => Boolean(i));
//     // obj = obj.filter(i => !!Boolean(i)); ✅
//     // obj = obj.filter(i => Boolean(i) !== false); ✅
//     temp = [];
//   } else {
//     temp = {};
//   }
//   for(let key in obj) {
//     if(Boolean(obj[key]) !== false) {
//       // if(Object.prototype.toString.call(obj[key]).includes(`object`)) { ❌ bug
//       if(Array.isArray(obj[key]) || Object.prototype.toString.call(obj[key]) === `[object Object]`) {
//         temp[key] = compactObject(obj[key]);
//       } else {
//         temp[key] = obj[key];
//       }
//     }
//   }
//   return temp;
// };

// function compactObject(obj: Obj): Obj {
//   let temp;
//   if(Array.isArray(obj)) {
//     obj = obj.filter(i => Boolean(i) !== false);
//     for(let i = 0; i < obj.length; i++) {
//       if(Boolean(obj[i]) !== false) {
//         if(Array.isArray(obj[i])) {
//           obj.splice(i, 1, compactObject(obj[i]));
//         }
//       } else {
//         obj.splice(i, 1);
//       }
//     }
//   } else {    
//     for(let key in obj) {
//       if(Boolean(obj[key]) !== false) {
//         if(Array.isArray(obj[key])) {
//           obj[key] = compactObject(obj[key]);
//         }
//       } else {
//         delete obj[key];
//       }
//     }
//   }
//   return obj;
// };


 /* 

 Wrong Answer ❌
69 / 156 testcases passed

Input
obj =
{"o":11,"a":68,"m":18,"v":true,"b":false,"h":null,"r":false,"p":93,"l":true,"k":"","n":79,"f":18,"u":null,"j":null,"e":null,"z":{"d":true,"t":null,"o":21,"w":null,"m":82,"k":35,"l":26,"r":45,"b":false,"z":0,"i":null,"c":33,"p":69,"j":27,"e":53,"q":97,"h":true,"a":true,"n":true,"f":73,"u":null},"w":12,"y":0,"q":"","t":null,"s":true,"x":false,"c":true,"i":false,"g":29}

Use Testcase
Output
{"o":11,"a":68,"m":18,"v":true,"p":93,"l":true,"n":79,"f":18,"z":{"d":true,"t":null,"o":21,"w":null,"m":82,"k":35,"l":26,"r":45,"b":false,"z":0,"i":null,"c":33,"p":69,"j":27,"e":53,"q":97,"h":true,"a":true,"n":true,"f":73,"u":null},"w":12,"s":true,"c":true,"g":29}
Expected
{"a":68,"c":true,"f":18,"g":29,"l":true,"m":18,"n":79,"o":11,"p":93,"s":true,"v":true,"w":12,"z":{"a":true,"c":33,"d":true,"e":53,"f":73,"h":true,"j":27,"k":35,"l":26,"m":82,"n":true,"o":21,"p":69,"q":97,"r":45}}
 
  */

簡化版 測試用例


// 簡化版 測試用例 

// 1. 物件套物件
{"a": null, "b": [false, 1], "c": {"d": null, "e": [true, 2, {"f": 3}]}}

// 2. 陣列套物件/陣列套陣列
[null, 0, false, 1, {"a": null, "b": [true, 2, {"c": 3}]}]

(🐞 反爬蟲測試!打擊盜版⚠️)如果你看到這個資訊, 說明這是一篇剽竊的文章,請訪問 https://www.cnblogs.com/xgqfrms/ 檢視原創文章!

Object.prototype.toString()

Object.prototype.toString.call(null)
'[object Null]'
Object.prototype.toString.call({})
'[object Object]'
Object.prototype.toString.call([])
'[object Array]'

typeof null
'object'
typeof {}
'object'
typeof []
'object'

Object.prototype.toString([])
'[object Object]'

const toString = Object.prototype.toString;

toString.call(new Date()); // [object Date]
toString.call(new String()); // [object String]
// Math has its Symbol.toStringTag
toString.call(Math); // [object Math]

toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]

refs

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString#using_tostring_to_detect_object_class

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 釋出文章使用:只允許註冊使用者才可以訪問!

原創文章,版權所有©️xgqfrms, 禁止轉載 🈲️,侵權必究⚠️!


相關文章