FE-Interview icon indicating copy to clipboard operation
FE-Interview copied to clipboard

请实现一个 JSON.stringfy

Open lgwebdream opened this issue 5 years ago • 3 comments

lgwebdream avatar Jul 06 '20 17:07 lgwebdream

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

lgwebdream avatar Jul 06 '20 17:07 lgwebdream


const jsonStringfy = source => {
  let result = "";
  const cache = new Map();

  const dp = data => {
    const values = [];
    Object.keys(data).forEach(key => {
      if (data[key] instanceof Object) {
        if (cache.has(data[key])) {
          values.push(`"${key}":${cache.get(data[key])}`);
        } else {
          const dataStr = dp(data[key]);
          cache.set(data[key], dataStr);
          values.push(`"${key}":${dataStr}`);
        }
      } else {
        values.push(`"${key}":"${data[key]}"`);
      }
    });

    return result + `{${values.join(",")}}`;
  };

  return dp(source);
};
image

gaohan1994 avatar May 03 '24 10:05 gaohan1994

 function myparse(source){
            
            let re=''
            let cache=new Map()
            let dp = (obj)=>{
                let values=[]
                for(let key in obj){

                    if(typeof obj[key]==='object') {
                        if(cache.get(obj[key])){
                            values.push(`"${key}":${cache.get(obj[key])}`)
                            //“”是json标准要求
                        }
                        else {
                            let datastr= dp(obj[key])
                            cache.set(obj[key],datastr)
                            values.push(`"${key}":${datastr}`)
                        }
                    } else values.push(`"${key}":${obj[key]}`)

                }
                re=`{${values.join(',')}}`
                return re
                
            }
            return dp(source)
        }
      
    // 测试示例
    const obj1 = { a: 1, b: { c: 2 }, d: null };
    const obj2 = { name: "Alice", age: 25, hobbies: ["reading", "gaming"] };
    const obj3 = { foo: { bar: { baz: 3 } }, qux: "hello" };
    const obj4 = { a: 1, b: 2, c: { d: 3, e: { f: 4 } } };

    console.log(myparse(obj1)); // 输出: {"a":"1","b":{"c":"2"},"d":null}
    console.log(myparse(obj2)); // 输出: {"name":"Alice","age":"25","hobbies":"reading,gaming"}
    console.log(myparse(obj3)); // 输出: {"foo":{"bar":{"baz":"3"}},"qux":"hello"}
    console.log(myparse(obj4)); // 输出: {"a":"1","b":"2","c":{"d":"3","e":{"f":"4"}}}

Alicca-miao avatar Oct 01 '24 12:10 Alicca-miao