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

203
Vistas
Flatten Object in-place in JavaScript

In a recent interview, I was asked to create a flat method which flattens an object. I tried to implement it like following, but it doesn't work:

Object.defineProperty(Object.prototype, 'flat', {
  enumerable: false,
  writable: true,
  configurable: false,
  value: function() {
      function flatten(obj) {
      for(let key in obj) {
        if(obj.hasOwnProperty(key)) {
          if(typeof obj[key] === 'object') {
            obj[key] = flatten(obj[key])
          }
          else {
           obj[key] = obj[key];
          }
        }
      }
      return obj;
    }
  flatten(this);
  }
});

var obj = { a: 1, b: 2, c: { d: { e: 5 }, f: 6 } }
obj.flat();
console.log(obj); // should return { a: 1, b: 2, e: 5, f: 6 }

What's wrong in my code?

PS: Other post on SO for flattening Object don't do it in-place, which is the requirement in this case.

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

0

You're creating the same recursive object structure here:

obj[key] = flatten(obj[key])

You need to put the nested properties onto the original object instead. You also need to remove the intermediate properties from the original object, so that you're left with only the properties at the end.

I'd also highly, highly recommend against mutating built-in prototypes, especially Object.prototype - it can lead to compatibility issues and confusing behavior, especially when libraries are involved. Things will break eventually as a result. Use a plain function instead.

const flatten = (base, obj = base) => {
  for (const [key, value] of Object.entries(obj)) {
    if (typeof value === 'object' && value !== null) {
      delete obj[key];
      flatten(base, value);
    } else {
      base[key] = value;
    }
  }
};
var obj = {
  a: 1,
  b: 2,
  c: {
    d: {
      e: 5
    },
    f: 6
  }
}
flatten(obj);
console.log(obj);

about 4 years ago · Juan Pablo Isaza Denunciar

0

With help from the other answer, I got the exact code I wanted:

Object.defineProperty(Object.prototype, 'flat', {
  enumerable: false,
  writable: true,
  configurable: false,
  value: function() {
      function flatten(base, obj) {
        for(let key in obj) {
          if(obj.hasOwnProperty(key)) {
            if(typeof obj[key] === 'object' && obj[key] !== null) {
              flatten(base, obj[key]);
              delete obj[key];
            }
            else {
             base[key] = obj[key];
            }
          }
        }
      }
    flatten(this, this);
  }
});

var obj = { a: 1, b: 2, c: { d: { e: 5 }, f: 6 } }
obj.flat();
console.log(obj); // returns { a: 1, b: 2, e: 5, f: 6 }

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