[英]Dynamically set property name of JavaScript object inside a function
I'm learning to build APIs with Express.我正在学习使用 Express 构建 API。 I figured that every time I have to send a successful JSON response, I have to duplicate most of the code.我想每次我必须发送成功的 JSON 响应时,我都必须复制大部分代码。 So I tried to put it in a function like so in one of my controller modules:因此,我尝试将其放入 function 中,就像在我的 controller 模块之一中一样:
const successResponse = (res, statusCode, obj, coll = false) => {
const successObj = { status: "success" };
if (coll) successObj.results = obj.length;
successObj.data = { obj };
return res.status(statusCode).json(successObj);
};
exports.getPlayer = asyncErrorHandler(async (req, res, next) => {
const player = await Player.findById(req.params.id);
if (!player) return next(new AppError("Player not found", 404));
successResponse(res, 200, player);
}
The problem is in the line successObj.data = { obj }
where I want the result to be the name of the argument that is passed as key and the object as value(s).问题出在successObj.data = { obj }
行中,我希望结果是作为键传递的参数的名称,并将 object 作为值传递。 The result I currently get is:我目前得到的结果是:
{
"status": "success",
"data": {
"obj": { // I want this key to be "player" here
"name": "Sal"
}
}
}
As the comment says I would like the key to be the string that I passed as the object name.正如评论所说,我希望密钥是我作为 object 名称传递的字符串。 I can do it by passing another argument as a string but it will always be the same as the object name that I pass.我可以通过将另一个参数作为字符串传递来做到这一点,但它始终与我传递的 object 名称相同。 Is there a better way to do this?有一个更好的方法吗?
You are getting a single object and trying to use that as key and value.您将获得一个 object 并尝试将其用作键和值。 You can try something like this:你可以尝试这样的事情:
Suppose your obj is假设你的 obj 是
var obj = { player: {
"name": "Sal"
}}
then while pushing to data you can follow these steps:然后在推送数据时,您可以按照以下步骤操作:
var selectedKey = Object.keys(obj)[0]; // assuming you will have a single key, if you have multiple then select based on the index
var selectedKeyData = Object.values(obj)[0];
var data = {};
data[selectedKey] = selectedKeyData;
Now, your data will have desired result.现在,您的数据将获得所需的结果。
You pass the name to the successResponse like this:您将名称传递给successResponse,如下所示:
exports.getPlayer = asyncErrorHandler(async (req, res, next) => {
const player = await Player.findById(req.params.id);
if (!player) return next(new AppError("Player not found", 404));
successResponse(res, 200, {objName: "player" , value: player);
}
And then change your successResponse like this:然后像这样改变你的successResponse:
// Set a suitable default value for objName (e.g. "obj") if you don't want to send it every time
const successResponse = (res, statusCode, {objName = "obj", value}, coll = false) => {
const successObj = { status: "success" };
if (coll) successObj.results = obj.length;
successObj.data = { [objName]: {value}}; // { player : { name : "Sal"} }
return res.status(statusCode).json(successObj);
};
EDIT 1 => NOTE: You can't access the name of the variable that passed to a function unless the name string was explicitly passed.编辑 1 => 注意:除非明确传递了名称字符串,否则您无法访问传递给 function 的变量的名称。 Because only the value that a variable held is passed along not the name.因为仅传递变量所持有的值而不是名称。 This why you have to pass it the name.这就是为什么你必须传递它的名字。 The solution I gave would not need another argument to function but it will need another key/value inside the object passed.我给出的解决方案不需要 function 的另一个参数,但它需要在 object 中传递另一个键/值。
**EDIT 2 => ** Even more cleaner solution **编辑 2 => ** 更清洁的解决方案
exports.getPlayer = asyncErrorHandler(async (req, res, next) => {
const player = await Player.findById(req.params.id);
if (!player) return next(new AppError("Player not found", 404));
successResponse(res, 200, {player}); //Same as {"player" : player}
}
And then change your successResponse like this:然后像这样改变你的successResponse:
const successResponse = (res, statusCode, obj, coll = false) => {
const successObj = { status: "success" };
if (coll) successObj.results = obj.length;
successObj.data = { ...obj };
return res.status(statusCode).json(successObj);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.