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

273
Vistas
How to loop inside a map() loop?

The below script outputs

================================================
Log entry ID: 1
UUID: 2
Timestamp: 3
--------------------
Log entry ID: 4
UUID: 5
Timestamp: 6

which is what I want.

Right now description is hard coded, where I would like it to be built using arr instead.

My current thinking were to somehow generate the inner array in the map() function:

[
    `Log entry ID: ${element['_id']}`,
    `UUID: ${element['_source'].uuid}`,
    `Timestamp: ${element['_source']['@timestamp']}\n`,
]

but because of the templating, this is not even a valid array with 3 elements, when looking at it on its own. So I am all out of ideas.

Question

Somehow I have to loop over the elements in arr before it is given to map(), I suppose.

Does anyone know how that could be done?

const dedent = require('dedent');

const arr = [
  [ 'Log entry ID', '_id' ],
  [ 'UUID', 'uuid' ],
  [ 'Timestamp', '@timestamp' ],
]
;

const docs = [
  {'_id': 1,'_source': {'uuid': 2,'@timestamp': 3}},
  {'_id': 4,'_source': {'uuid': 5,'@timestamp': 6}},
];

const description = dedent`
================================================
${
  docs.map((element) => [
    `Log entry ID: ${element['_id']}`,
    `UUID: ${element['_source'].uuid}`,
    `Timestamp: ${element['_source']['@timestamp']}\n`,
  ].join('\n')).join('--------------------\n')
}
`;

console.log(description);

Update

I control arr so changing it to eg. is possible, or something else

const arr = [
  [ 'Log entry ID', '_id' ],
  [ 'UUID', {'_source': 'uuid'} ],
  [ 'Timestamp', {'_source': '@timestamp'} ],
]
;
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Since arr is in your control perhaps you can specify the path of the key itself.

const arr = [
  ['Log entry ID', '_id'],
  ['UUID', '_source.uuid'],
  ['Timestamp', '_source.@timestamp'],
  ['Description', '_source._desc']
];

const docs = [{
    '_id': 1,
    '_source': {
      'uuid': 2,
      '@timestamp': 3,
      '_desc': 'test 1'
    }
  },
  {
    '_id': 4,
    '_source': {
      'uuid': 5,
      '@timestamp': 6,
      '_desc': 'test 2'
    }
  },
];

const getValue = (object, keys) => keys.split('.').reduce((o, k) => (o || {})[k], object);

console.log(docs.map((element) => arr.map((label) => {
  return `${label[0]}: ${getValue(element, label[1])}`
}).join('\n')).join('\n--------------------\n'))

about 4 years ago · Juan Pablo Isaza Denunciar

0

Assuming that the keys of a docs array element are all unique, one could traverse the object looking for a matching key.

function findVal(object, key) {
    var value;
    Object.keys(object).some(function(k) {
        if (k === key) {
            value = object[k];
            return true;
        }
        if (object[k] && typeof object[k] === 'object') {
            value = findVal(object[k], key);
            return value !== undefined;
        }
    });
    return value;
}


docs.map((element) =>
arr.map(([item, key]) =>
    `${item}: ${findVal(element, key)}`)
)

The FindVal is taken from here.

about 4 years ago · Juan Pablo Isaza Denunciar

0

you could create a function to get data from arr and put in description

/* Simple Hello World in Node.js */

const arr = [
  [ 'Log entry ID', '_id' ],
  [ 'UUID', 'uuid' ],
  [ 'Timestamp', '@timestamp' ],
]
;

const docs = [
  {'_id': 1,'_source': {'uuid': 2,'@timestamp': 3}},
  {'_id': 4,'_source': {'uuid': 5,'@timestamp': 6}},
];
const findInArr=function(value){
    var t = ""
    arr.forEach(item=>{
        if (item.includes(value)) {t = item[0]}
        
    })
    return t
}
const description = dedent`
================================================
 ${
 docs.map((element) => [
    `${findInArr('_id')}: ${element['_id']}`,
    `${findInArr('UUID')}: ${element['_source'].uuid}`,
    `${findInArr('Timestamp')}: ${element['_source']['@timestamp']}\n`,
  ].join('\n')).join('--------------------\n')
}`;

console.log(description);
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