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

237
Vistas
Spread operator with reduce function in js

I trying to generate all possible paths of the given json object. Some how I generated the paths but I want my final array in a flatten manner (no nested arrays inside the final array). I tried speading the array, but the final array contains some nested arrays. I want to have all the elements in a flatter manner.

Current op:

[
  "obj",
  "level1.level2.level3.key",
  [
    "arrayObj.one[0].name",
    "arrayObj.one[0].point"
  ]
]

Expected:

[
  "obj",
  "level1.level2.level3.key",
  "arrayObj.one[0].name",
  "arrayObj.one[0].point"
]

Below I have attached the snippet I tried.

const allPaths = (obj, path = "") =>
  Object.keys(obj).reduce((res, el) => {
    if (Array.isArray(obj[el]) && obj[el].length) {
      return [...res, ...obj[el].map((item, index) => {
        return [...res, ...allPaths(item, `${path}${el}[${index}].`)];
      })];
    } else if (typeof obj[el] === "object" && obj[el] !== null) {
      return [...res, ...allPaths(obj[el], `${path}${el}.`)];
    }
    return [...res, path + el];
  }, []);

const obj = {
  obj: 'sample',
  level1: {
    level2: {
      level3: {
        key: 'value'
      }
    }
  },
  arrayObj: {
    one: [{
        name: 'name',
        point: 'point'
      },
      {
        name: 'name2',
        point: 'point2'
      },
      {
        name: 'name2',
        point: 'point2'
      }
    ]
  }
}

console.log(allPaths(obj));

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

0

UPDATE: I didn't understood the question previously correctly. Now i do. So yes the below code will solve the problem for you.

You want your object to be flattened with dots

If thats the case the below should work

const obj = {
  obj: 'sample',
  level1: {
    level2: {
      level3: {
        key: 'value'
      }
    }
  },
  arrayObj: {
    one: [{
        name: 'name',
        point: 'point'
      },
      {
        name: 'name2',
        point: 'point2'
      },
      {
        name: 'name2',
        point: 'point2'
      }
    ]
  }
}

function flatten(data, prefix) {
  let result = {}
  for(let d in data) {
    if(typeof data[d] == 'object') Object.assign(result, flatten(data[d], prefix + '.' + d))
    else result[(prefix + '.' + d).replace(/^\./, '')] = data[d]
  }
  return result
}

console.log(flatten(obj, ''))

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