Adam91Holt Adam91Holt - 1 year ago 59
Node.js Question

Convert an object with key values to an array of objects with said key name and values

Im getting my head stuck in a twist with this one...

Im trying to convert my req.query I get in Express which is an object to make an array of objects so I can pass these through to mssql as inputs for stored procedures.

This is the data I have -

{ param1: 'testing123', param2: 'poooool', param300: 'nnnvncn' }

I wan't it to appear like

[{param1: 'testing123'},{param2: 'poooool'},{param300: 'nnnvncn'}]

Any idea how I would get to the desired array above?

EDIT: This is the code I went for in the end running in node.js

app.get('/:client/storedproc/:sp', function(req, resp){
var sp = req.params.sp;
var obj = req.query;
var test = function(){ return Object.keys(obj).map(k => ({ [k]: obj[k] }));}
var arr = test();

Answer Source

You can use Object.keys for this. Given the object from your first snippet o:

return Object.keys(o).map(function(k) {
    var x = {};
    x[k] = o[k];
    return x;

Just for fun, here's how terse it is with ES2015:

return Object.keys(o).map(k => ({ [k]: o[k] }));