简体   繁体   中英

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

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)
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM