JSON.stringify replacer - how to get full path

后端 未结 5 2077
太阳男子
太阳男子 2021-01-07 07:35

Replacer in below code write on console current processed field name

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-07 08:17

    You can use custom walk function inside your replacer. Here's an example using a generator walk function:

    const testObject = {a: 1, b: {a: 11, b: {a: 111, b: 222, c: 333}}, c: 3};
    
    function* walk(object, path = []) {
        for (const [key, value] of Object.entries(object)) {
            yield path.concat(key);
    
            if (typeof value === 'object') yield* walk(value, path.concat(key));
        }
    }
    
    const keyGenerator = walk(testObject);
    
    JSON.stringify(testObject, (key, value) => {
        const fullKey = key === '' ? [] : keyGenerator.next().value;
    
        // fullKey contains an array with entire key path
        console.log(fullKey, value);
    
        return value;
    });
    

    Console output:

      fullKey          |  value
    -------------------|------------------------------------------------------------
      []               |  {"a":1,"b":{"a":11,"b":{"a":111,"b":222,"c":333}},"c":3}
      ["a"]            |  1
      ["b"]            |  {"a":11,"b":{"a":111,"b":222,"c":333}}
      ["b", "a"]       |  11
      ["b", "b"]       |  {"a":111,"b":222,"c":333}
      ["b", "b", "a"]  |  111
      ["b", "b", "b"]  |  222
      ["b", "b", "c"]  |  333
      ["c"]            |  3
    

    This works, assuming the algorithm in replacer is depth-first and consistent across all browsers.

提交回复
热议问题