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

246
Vistas
How to merge specific property names and concatenate theirs values upon certain conditions?

I've got this type of dataset :

[
  {
    CODMAT: '86        ',
    LIBMAT: 'Chariot N.50 Damien           ',
    CODCAR: 'I050DCHE  ',
    ZONLST: 'A',
    ALLLST: 1,
    CIRMAT1: 'AUA',
    CIRMAT2: 'SUC',
    CIRMAT3: 'SAL',
    CIRMAT4: 'AU3',
    CIRMAT5: '   ',
    CIRMAT6: '   '
  },
  {
   ...
  }
]

I would like to concatenate all the 'CIRMAT' data and delete these which are empty, like this :

  {
    CODMAT: '86        ',
    LIBMAT: 'Chariot N.50 Damien           ',
    CODCAR: 'I050DCHE  ',
    ZONLST: 'A',
    ALLLST: 1,
    CIRMAT: ['AUA','SUC','SAL','AU3']
  }

Thanks for your help

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

0

You can use Object.entries(), map() and reduce() together to achieve what you want.

Checking for an empty string happens by using trim() which removes leading and trailing whitespace from the string and then checking the length of the string.

const input = [
  {
    CODMAT: '86        ',
    LIBMAT: 'Chariot N.50 Damien           ',
    CODCAR: 'I050DCHE  ',
    ZONLST: 'A',
    ALLLST: 1,
    CIRMAT1: 'AUA',
    CIRMAT2: 'SUC',
    CIRMAT3: 'SAL',
    CIRMAT4: 'AU3',
    CIRMAT5: '   ',
    CIRMAT6: '   '
  },
]

const output = input.map(item => (
  Object.entries(item).reduce((newObj, [key, value]) => {
    if(key.startsWith("CIRMAT") && typeof value === "string"){
      // ignore values that are "empty"
      if(value.trim().length === 0) return newObj;
      if(!newObj.CIRMAT) newObj.CIRMAT = [value];
      else newObj.CIRMAT.push(value); 
    }
    else{
      // just assign the same key the same value
      newObj[key] = value;
    }
    return newObj;
  }, {})
))

console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }

  1. map() is required to map each value in the input array 1:1 to a value in the output array.
  2. reduce() will do the transformation of a single item within the array. If the key starts with CIRMAT we need to check whether we already have a CIRMAT property on our working object newObj. If we have not, this is the first CIRMATx property and we need to create an array containing the value. If we already have an array and just need push() the new value to it. In case the key does not start with CIRMAT we just add the value and key to our working object newObj without any changes.
about 4 years ago · Juan Pablo Isaza Denunciar

0

An approach which covers the naming schema of any to be merged key/property name generically needs to go through all of an item's entries (key-value pairs) where it would separate each key into its digit-less normalized property name and its digit only suffix (the trailing number) part. Then it would merge/collect only entries which feature both, the new key and the to be discarded number where in addition the value is not empty (or just a whitespace sequence).

Thus one might use ...

  • a regex like ... /^(\D+)(\d+)?$/ ... which matches the pattern of a digit-less leading string and a digit-only trailing string where both substrings are being captured.

  • Array.prototype.map in order to create a new array of changed/merged items.

  • Object.entries in order to get the key-value pairs of each to be mapped array item.

  • Array.prototype.reduce in order to process (merge and/or collect) each entry of the to be mapped array item.

function mergeEquallyNamedButNumberedEntries(item) {
  const regXNumberedKey = /^(\D+)(\d+)?$/;

  return Object
    .entries(item)
    .reduce((merger, [key, value]) => {

      const [
        match,
        mergerKey = null,
        trailingNumber = null,
      ] =
        key.match(regXNumberedKey) ?? [];

      if (mergerKey !== null) {
        if (trailingNumber !== null) {
          if (String(value ?? null).trim() !== '') {

            (merger[mergerKey] ??= []).push(value);
          }
        } else {
          merger[mergerKey] = value;
        }
      }
      return merger;

    }, {});
}

const sampleData = [{
  CODMAT: '86        ',
  LIBMAT: 'Chariot N.50 Damien           ',
  CODCAR: 'I050DCHE  ',
  ZONLST: 'A',
  ALLLST: 1,
  CIRMAT1: 'AUA',
  CIRMAT2: 'SUC',
  CIRMAT3: 'SAL',
  CIRMAT4: 'AU3',
  CIRMAT5: '   ',
  CIRMAT6: '   '
}, {
  foo: 567,
  bar: 'baz',
  baz99: '  ',
  baz88: ' ',
  baz77: '',
  biz11: '',
  biz22: ' ',
  biz33: 'foo', 
}];

const result = sampleData
  .map(mergeEquallyNamedButNumberedEntries);

console.log({ result, sampleData });
.as-console-wrapper { min-height: 100%!important; top: 0; }

about 4 years ago · Juan Pablo Isaza Denunciar

0

This should work :

    const data = [
      {
        CODMAT: '86        ',
        LIBMAT: 'Chariot N.50 Damien           ',
        CODCAR: 'I050DCHE  ',
        ZONLST: 'A',
        ALLLST: 1,
        CIRMAT1: 'AUA',
        CIRMAT2: 'SUC',
        CIRMAT3: 'SAL',
        CIRMAT4: 'AU3',
        CIRMAT5: '   ',
        CIRMAT6: '   '
      },
    ]

    const output = input.map(item => (
      Object.entries(item).reduce((formatted, [key, value]) => {
        if(key.startsWith("CIRMAT") && typeof value === "string"){
          if(value.trim().length === 0) return formatted;
          if(!formated.CIRMAT) formatted.CIRMAT = [value];
          else formatted.CIRMAT.push(value); 
        }
        else{
          formatted[key] = value;
        }
        return formatted;
      }, {})
    ))

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