0

I'm getting my head stuck in a twist with this one...

I'm 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 SQL Server as inputs for stored procedures.

This is the data I have -

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

I want 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();
    console.log(arr)
});
1
  • Re your edit: I would double check this actually works. I'm not sure if Node natively supports all the fancy ES2015 stuff. Commented Aug 14, 2016 at 7:05

1 Answer 1

1

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] }));
Sign up to request clarification or add additional context in comments.

3 Comments

Damn that ES2015 is beautiful - I need to start learning so much more JS :) Thanks Asad - I will update my post above with what I went for in the end.
@Adam91Holt And that actually works in Node JS without a transpiler?
@Adam91Holt Btw, you don't need to create a separate test function there since you're closing over o anyway. Just do var arr = Object.keys(obj).map(k => ({ [k]: obj[k] }));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.