【问题标题】:JavaScript: how do I flatten an object like thisJavaScript:我如何展平这样的对象
【发布时间】:2021-10-27 01:01:03
【问题描述】:

我们如何实现一个 util flatten 来扁平化这个

myMap = {
  'a': 5,
  'b': 6,
  'c': {
    'f': 9,
    'g': {
      'm': 17,
      'n': 3
    }
  }
}

flatten(myMap) = {
  'a': 5,
  'b': 6,
‍‌‌‍‌‍‌‍‍‌‍‍‍‍‍‌‍‌‍‍ 'c.f': 9,
  'c.g.m': 17,
  'c.g.n': 3,
}

?

我在这里找到了一个实现https://github.com/lukeed/flattie/blob/master/src/index.js,但我看不懂代码。谁能给我一个更易读的版本?

【问题讨论】:

  • 在我看来,这非常清晰和直截了当。您能否解释一下究竟是什么问题,以便我们帮助解决?
  • 基本上就是遍历一棵树,写下每一片叶子的整个路径。

标签: javascript


【解决方案1】:

您可以使用此代码:

myMap = {
  'a': 5,
  'b': 6,
  'c': {
    'f': 9,
    'g': {
      'm': 17,
      'n': 3
    }
  }
}

function flatten(obj, pKey = null, res = {}) {
  for (let key in obj) {
    const name = pKey ? `${pKey}.${key}` : key;
    if (typeof obj[key] === "object" && !Array.isArray(obj[key])) {
      flatten(obj[key], name, res);
    } else {
      res[name] = obj[key];
    }
  }
  return res;
}

console.log(flatten(myMap))

您可以通过flatten(myMap) 使用它。实际上,这很简单,但有时会让人感到困惑。它的工作原理是循环然后检查,如果它是一个对象,然后再次调用自身(递归)以深入创建一个关键对象,如果不是,则创建一个关键对象直到那里。

【讨论】:

    【解决方案2】:

    这可能是一个稍微简单的版本:

    const inputObject = {
      a: 5,
      b: 6,
      c: {
        f: 9,
        g: {
          m: 17,
          n: 3
        }
      }
    }
    
    function flatten(input, keys = [], output = {}) {
      for (key in input) {
        const value = input[key]
        const combinedKeys = [...keys, key]
    
        if (typeof value === 'object') {
          output = flatten(value, combinedKeys, output)
        } else {
          output[combinedKeys.join('.')] = value
        }
      }
      return output
    }
    
    console.log(flatten(inputObject))
    /* Logs:
     * {
     *   "a": 5,
     *   "b": 6,
     *   "c.f": 9,
     *   "c.g.m": 17,
     *   "c.g.n": 3
     * }
     */

    我们的想法是递归地查看对象的所有属性并构建一个.-分隔键,随着我们深入,直到我们达到叶值。

    您可以在此处阅读有关递归函数的更多信息:https://www.freecodecamp.org/news/what-is-recursion-in-javascript/

    【讨论】:

      【解决方案3】:

      这是一种选择:

      // Declare an object
      myMap = {
          'a': 5,
          'b': 6,
          'c': {
            'f': 9,
            'g': {
               'm': 17,
               'n': 3
        }
       }
      }
      // Declare a flatten function that takes
      // object as parameter and returns the
      // flatten object
      const flattenObj = (myMap) => {
      
      // The object which contains the
      // final result
      let result = {};
      
      // loop through the object "ob"
      for (const i in myMap) {
      
          // We check the type of the i using
          // typeof() function and recursively
          // call the function again
          if ((typeof myMap[i]) === 'object' && !Array.isArray(myMap[i])) {
              const temp = flattenObj(myMa**strong text**p[i]);
              for (const j in temp) {
      
                  // Store temp in result
                  result[i + '.' + j] = temp[j];
              }
          }
      
          // Else store ob[i] in result directly
          else {
              result[i] = myMap[i];
          }
      }
      return result;
      };
      
      console.log(flattenObj(myMap));
      

      【讨论】:

        猜你喜欢
        • 2020-06-23
        • 2016-12-26
        • 2018-02-24
        • 2015-05-23
        • 2020-12-22
        • 2018-04-27
        • 2016-06-27
        • 2023-01-11
        • 2020-10-24
        相关资源
        最近更新 更多