Node JS中的地图操作

时间:2018-06-03 00:22:20

标签: javascript node.js lodash

由于我在地图中有4个键/值,我正在尝试以字符串格式存储两个键,并将两个键存放在数组中。

现在我得到了什么输出:

{ url: 'account/43',    
  status: '200',    
  headers: '\'content-type\' = \'application/json\'',    
  body: '{ name: Fatma Zaman }' }

预期产出:

{ url: 'account/43',    
  status: '200',    
  headers: [ '\'content-type\' = \'application/json\'' ],    
  body: [ '{ "name": "Fatma Zaman" }' ]}

下面是返回字符串中所有键/值对的代码,我可以在数组中创建所有键/值对但不确定如何只对数组执行两个键的值。

function processFile(content) {

  lodash.forEach(content, function(node) {

    if (node.startsWith("//")) {

      key = node.substring(2, node.length - 2).toLowerCase().trim()
      return

    } else {
      value = node
    }

    map[key] = value
  })

  console.log(lodash.map(map, "key"))
  return map

}

1 个答案:

答案 0 :(得分:0)

您可以根据键名添加简单条件,并将值放在数组

  

map [key] = [' header',' body']。includes(key)? [value]:值;

function processFile(content) {
  lodash.forEach(content, function(node) {
    if (node.startsWith('//')) {
      key = node
        .substring(2, node.length - 2)
        .toLowerCase()
        .trim();
      return;
    } else {
      value = node;
    }

    map[key] = ['header', 'body'].includes(key) ? [value] : value;
  });
  return map;
}
相关问题