0

I have a node.js mysql query:

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

The result I'm getting back locks like this:

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' }];

To further cosume the result ... I need an additional paremeter 'type' with with a fixed value in the array. So result should look like this:

[ { 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' }];       

What's the fastest/best way to do this? Looping over the array? How should it look like?

Philipp M
  • 3,306
  • 5
  • 36
  • 90
  • Possible duplicate of [Add key value pair to all objects in array](https://stackoverflow.com/questions/39827087/add-key-value-pair-to-all-objects-in-array) – oreopot Nov 29 '18 at 22:54

2 Answers2

3

Use the map method:

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

Or forEach, this will modify your array:

array1.forEach(element => element.type = 'ABC');
console.log(array1);
Ivan
  • 203
  • 1
  • 8
1
    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);
oreopot
  • 3,392
  • 2
  • 19
  • 28