Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

232
Vistas
JavaScript: how do I flatten an object like this

how do we implement a util flatten to flat this

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

to

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

?

I found here is an implementation https://github.com/lukeed/flattie/blob/master/src/index.js but I couldn't understand the code. Can someone please give me a more readable version?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can use this code:

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))

you can use it by flatten(myMap). Actually, it's simple, but sometimes it makes confusion. how it works is by looping then checking, if it is an object then calling itself again (recursive) to create a key object deeply and if not then create a key object until there.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Here is perhaps a slightly simpler version:

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
 * }
 */

The idea is to recursively look at all properties of the object and build a .-separated key as we go deeper until we reach a leaf value.

You can read more about recursive functions here: https://www.freecodecamp.org/news/what-is-recursion-in-javascript/

about 4 years ago · Juan Pablo Isaza Denunciar

0

Here's one option:

// 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));
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda