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

182
Vistas
How to convert an arbitrarily nested object into tabular structure a reversible way?

Given an arbitrarily deep nested object whose structure it not known until runtime, such as

    {
      "row-0" : {
        "rec-0" : {
          "date" : 20220121,
          "tags" : [ "val-0" ]
        },
        "rec-1" : {
          "date" : 20220116,
          "url" : "https://example.com/a",
          "tags" : [ "val-0", "val-1" ]
        }
      },
      "row-1" : {
        "rec-0" : {
          "date" : 20220116,
          "url" : "https://example.com/b"
        }
      }
    }

I want a tool / program to reversibly convert it to a tabular (2D) structure such as

    {
      "row-0" : {
        "['rec-0']['date']" : 20220121,
        "['rec-0']['tags'][0]" : "val-0",
        "['rec-1']['date']" : 20220116,
        "['rec-1']['url']" : "https://example.com/a",
        "['rec-1']['tags'][0]" : "val-0",
        "['rec-1']['tags'][1]" : "val-1"
        },
      "row-1" : {
        "['rec-0']['date']" : 20220116,
        "['rec-0']['url'']" : "https://example.com/b"       
      }
    }

This format falicates export as CSV and subsequent editing with a spreadsheet app. The paths of the original nested object are encoded in the keys (column headers) such as "['rec-0']['date']" and "['rec-0']['tags'][0]" to facilitate the reverse transformation.

What is the best approach to achieving this?

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

0

You can get it done using a simple recursive function that generates a nested key name and end value and populate it into an array.

Object.entries is handy in the solution as it can iterate either array or object using index or key respectively.

const data = { "row-0": { "rec-0": { date: 20220121, tags: ["val-0"], }, "rec-1": { date: 20220116, url: "https://example.com/a", tags: ["val-0", "val-1"], }, }, "row-1": { "rec-0": { date: 20220116, url: "https://example.com/b", }, }, };

const generateNestedKeyNameAndValue = (input, nestedKeyName, keyValueArr) => {
  if (typeof input === "object") {
    // array or object - iterate over them
    const quoteString = Array.isArray(input) ? "" : "'";
    Object.entries(input).forEach(([key, value]) => {
      generateNestedKeyNameAndValue(
        value,
        // extend the key name 
        `${nestedKeyName}[${quoteString}${key}${quoteString}]`,
        keyValueArr
      );
    });
  } else {
    // string or number (end value)
    keyValueArr.push([nestedKeyName, input]);
  }
};

const output = Object.fromEntries(
  Object.entries(data).map(([key, value]) => {
    const generatedKeyValuePairs = [];
    generateNestedKeyNameAndValue(value, "", generatedKeyValuePairs);
    return [key, Object.fromEntries(generatedKeyValuePairs)];
  })
);

console.log(output);

about 4 years ago · Juan Pablo Isaza Denunciar

0

Iterate the current entries using Array.map(). Generate the path according to the rules (see preparePath function). For each value, check if it's an object (or array). If it is add it's keys to the path. If not, return a { [path]: val } object. Flatten all objects by spreading into Object.assing().

// prepare the key from the current key, isArray(obj), and the previous path
const preparePath = (key, obj, path = []) => [
  ...path, 
  `[${Array.isArray(obj) ? key : `'${key}'`}]`
]

// convert all sub objects to a single object
const fn = (obj, path) => Object.assign({}, ...Object.entries(obj)
  .map(([key, val]) => typeof val === 'object' // if the value is an object
    ? fn(val, preparePath(key, obj, path)) // iterate it and it to current path
    : { [preparePath(key, obj, path).join('')]: val } // if the val is not an object, create an object of { [path]: val }
  ))

const data = {"row-0":{"rec-0":{"date":20220121,"tags":["val-0"]},"rec-1":{"date":20220116,"url":"https://example.com/a","tags":["val-0","val-1"]}},"row-1":{"rec-0":{"date":20220116,"url":"https://example.com/b"}}}

// iterate the 1st level of the object since and flatten each sub object
const result = Object.fromEntries(
  Object.entries(data).map(([k, v]) => [k, fn(v)])
)

console.log(result)

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