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

147
Vistas
Merge optional nested array values to create new object

There are multiple fields in an object like this.

{
  "image-processing": {
    "type": "lib",
    "data": {
      "files": [
        {
          "file": "libs/photography/processing/.babelrc",
          "hash": "62d50f586b2880f9d58ca4e9a84914c6a0d4936d"
        },
        {
          "file": "libs/photography/processing/src/lib/processing.ts",
          "hash": "a285d3554f264cc60f35bef6180298badb0478d1",
          "deps": [
            "npm:gm",
            "npm:mongodb"
          ]
        }
      ]
    }
  },
  "image-processing-2": {
    "type": "lib",
    "data": {
      "files": [
        {
          "file": "libs/photography/processing/.babelrc",
          "hash": "62d50f586b2880f9d58ca4e9a84914c6a0d4936d",
          "deps": [
            "npm:gm",
            "npm:faker"
          ]
        },
        {
          "file": "libs/photography/processing/src/lib/processing.ts",
          "hash": "a285d3554f264cc60f35bef6180298badb0478d1",
          "deps": [
            "npm:gm",
            "npm:mongodb"
          ]
        }
      ]
    }
  }
}

I only need the type and the content of data.files.deps as value object for the key. As you can see each file has an optional deps array. All deps values should be merged.

So the result should be:

{
    "image-processing": { type: "lib", packages: [ "npm:gm", "npm:mongodb" ] },
    "image-processing-2": { type: "lib", packages: [ "npm:faker", "npm:gm", "npm:mongodb" ] }
}

I tried to iterate through the object, but this would overwrite the value instead of adding new package names to the value:

const result = {}
Object.entries(data).map(([key, value]) => {
    result[key].type = value.type
    result[key].packages = value?.data?.files.map(d => d.deps)
})
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Use flatMap instead of map so that you have a flattened array of dependency strings - and alternate with the empty array so that undefined .deps properties don't cause problems.

const data={"image-processing":{type:"lib",data:{files:[{file:"libs/photography/processing/.babelrc",hash:"62d50f586b2880f9d58ca4e9a84914c6a0d4936d"},{file:"libs/photography/processing/src/lib/processing.ts",hash:"a285d3554f264cc60f35bef6180298badb0478d1",deps:["npm:gm","npm:mongodb"]}]}},"image-processing-2":{type:"lib",data:{files:[{file:"libs/photography/processing/.babelrc",hash:"62d50f586b2880f9d58ca4e9a84914c6a0d4936d",deps:["npm:gm","npm:faker"]},{file:"libs/photography/processing/src/lib/processing.ts",hash:"a285d3554f264cc60f35bef6180298badb0478d1",deps:["npm:gm","npm:mongodb"]}]}}};

const output = Object.fromEntries(
  Object.entries(data).map(([key, value]) => [
    key,
    {
      type: 'lib',
      packages: [...new Set(value.data.files.flatMap(file => file.deps ?? []))]
    }
  ])
);
console.log(output);

about 4 years ago · Juan Pablo Isaza Denunciar

0

Based on your new comments, just to separate the logic out a little:

Iterate over the Object.entries to get a key/value pair (the value is the object), and then iterate over the files of each object. If there are any deps filter out the "npm" ones, then map over that array and create a new one with the updated names.

Add that array to the packages array.

Finally flatten the packages array, dedupe it by creating a new Set from it, and then spreading that back out into an array as the value of the packages object you then add to the output object using the key.

const data={"image-processing":{type:"lib",data:{files:[{file:"libs/photography/processing/.babelrc",hash:"62d50f586b2880f9d58ca4e9a84914c6a0d4936d"},{file:"libs/photography/processing/src/lib/processing.ts",hash:"a285d3554f264cc60f35bef6180298badb0478d1",deps:["npm:gm","npm:mongodb"]}]}},"image-processing-2":{type:"lib",data:{files:[{file:"libs/photography/processing/.babelrc",hash:"62d50f586b2880f9d58ca4e9a84914c6a0d4936d",deps:["npm:gm","npm:faker"]},{file:"libs/photography/processing/src/lib/processing.ts",hash:"a285d3554f264cc60f35bef6180298badb0478d1",deps:["npm:gm","npm:mongodb"]}]}}};
// Output object
const out = {};

// Iterate over the object entries
for (const [key, obj] of Object.entries(data)) {
  
  // Destructure the type, and the files
  // array from each object
  const { type, data: { files } } = obj;
  
  const packages = [];

  // Iterate over each `files` array
  for (const file of files) {

    if (file.deps) {
      
      // `filter` out the "npm" names, and
      // then `map` over that array to update the names
      const list = file.deps
        .filter(dep => dep.startsWith('npm:'))
        .map(dep => dep.replace('npm:', ''));

      // Bang that completed array into `packages`
      packages.push(list);
    
    }

  }

  // Finally create a new key/value on the output
  // object by setting the value as an object
  // with `type`, and the flattened, deduped packages array
  out[key] = {
    type,
    packages: [...new Set(packages.flat())]
  };

}

console.log(out);

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