如何在 map() 循环内循环?

How to loop inside a map() loop?

下面的脚本输出

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

这就是我想要的。

现在 description 是硬编码的,我希望使用 arr 来构建它。

我目前的想法是以某种方式在 map() 函数中生成内部数组:

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

但是由于模板的原因,当单独查看时,这甚至不是一个包含 3 个元素的有效数组。所以我完全没有想法。

问题

我想我必须以某种方式循环遍历 arr 中的元素,然后再将其提供给 map()

有人知道怎么做吗?

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);

更新

我控制 arr 所以将其更改为例如。是可能的,或者别的什么

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

您可以创建一个函数来从 arr 获取数据并放入描述

/* 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);

由于 arr 在您的控制之下,也许您可​​以指定密钥本身的路径。

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'))

假设 docs 数组元素的键都是唯一的,可以遍历对象寻找匹配的键。

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)}`)
)

FindVal取自