flattenObject()

將物件的「多層結構」打為「單層結構」。

💾 程式:codesandbox - Object.js

/**
 * flatten a "multi-level" object to a flat one.
 * @param {object} obj - the object to be flattened
 */
export function flattenObject(obj) {
  // the flattened object
  let result = {};

  // try to add property to result with (key, value) pair
  function addProperty(key, value) {
    // base case:
    // `value` is not an object, add it to result directly.
    if (typeof value !== 'object') {
      result[key] = value;
      return;
    }
    // recursive case:
    // `value` is an object, try to add its properties to result
    for (let prop in value) {
      addProperty(`${key}${key ? '.' : ''}${prop}`, value[prop]);
    }
  }

  // begin to add properties from the root object
  addProperty('', obj);
  return result;
}

// ----------- test run ------------

const dict = {
  a: { a: 1, b: 2 },
  b: { a: 3, b: 4, c: 5 },
};

flattenObject(dict),
// {a.a: 1, a.b: 2, b.a: 3, b.b: 4, b.c: 5}

Last updated