【问题标题】:Javascript - Best/fastest way to add element to query result with fixed valueJavascript - 将元素添加到具有固定值的查询结果的最佳/最快方法
【发布时间】:2018-11-29 22:43:02
【问题描述】:

我有一个 node.js mysql 查询:

connection.query("SELECT id AS id, name AS label, status AS status from table;", function(err, rows) {
    ...
});

我得到的结果是这样的:

console.log(getBody)

[ { id: '1',
   label: 'Name 01',
   status: 'ACTIVE' },
 { id: '2',
   label: 'Name 02',
   status: 'INACTIVE' },
 { id: '3',
   label: 'Name 03',
   status: 'ACTIVE' },
 { id: '4',
   label: 'Name 04',
   status: 'ACTIVE' }];

为了进一步计算结果......我需要一个额外的参数“类型”,在数组中具有固定值。所以结果应该是这样的:

[ { id: '1',
   label: 'Name 01',
   status: 'ACTIVE',
   type: 'ABC' },
 { id: '2',
   label: 'Name 02',
   status: 'INACTIVE',
   type: 'ABC' },
 { id: '3',
   label: 'Name 03',
   status: 'ACTIVE',
   type: 'ABC' },
 { id: '4',
   label: 'Name 04',
   status: 'ACTIVE',
   type: 'ABC' }];       

最快/最好的方法是什么?循环数组?它应该是什么样子?

【问题讨论】:

标签: javascript mysql sql node.js


【解决方案1】:

使用map 方法:

const newArray = array1.map(element => element = {...element, ...{type: 'ABC'}});
console.log(array1); // array1 won't be changed
console.log(newArray);

或者forEach,这会修改你的数组:

array1.forEach(element => element.type = 'ABC');
console.log(array1);

【讨论】:

    【解决方案2】:
        var arr = [
       {id: '1',label: 'Name 01',status: 'ACTIVE'},
       {id: '2',label: 'Name 02',status: 'INACTIVE'},
       {id: '3',label: 'Name 03',status: 'ACTIVE'},
       {id: '4',label: 'Name 04',status: 'ACTIVE'}];
    
        var new_arr = arr.map(function(el) {
          var o = Object.assign({}, el);
          o. type = 'ABC';
          return o;
        })
    
        console.log(arr);
        console.log(new_arr);
    

    【讨论】:

      猜你喜欢
      • 2019-07-15
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 2013-06-27
      • 2013-08-25
      • 1970-01-01
      • 2013-03-17
      相关资源
      最近更新 更多