Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

230
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda