简体   繁体   English

将具有键值的对象转换为具有所述键名和值的对象数组

[英]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. 我正在尝试转换我在Express中获得的req.query,这是一个对象,用于形成对象数组,因此我可以将这些作为传递给存储过程的输入传递给SQL Server。

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 编辑:这是我最终在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. 您可以为此使用Object.keys Given the object from your first snippet o : 给定第一个片段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: 只是为了好玩,这就是ES2015的简洁程度:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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