test_query.py
在上面的函数中,我有一个可变的声明'imageName'。我只需要在'obj'处使用'imageName'变量得到的结果。假设我从req.body.name获得'alpha',那么我想在'obj'中使用它,如function abc(req, res, next) {
let imageName = req.body.name;
const obj = {
imageName: {
status: true,
url: "abc"
}
}
。
答案 0 :(得分:1)
您可以使用bracket notation为对象提供动态密钥。
let imageName = 'alpha';
const obj = {
[imageName]: {
status: true,
url: "abc"
}
}
console.log(obj);
您的代码将是
function abc(req, res, next) {
let imageName = req.body.name;
const obj = {
[imageName]: {
status: true,
url: "abc"
}
}
答案 1 :(得分:1)
如果我正确地阅读您的问题,您需要对对象使用括号表示法来获取动态键值:
function abc(req, res, next) {
const obj = {};
obj[req.body.name] = {status: true, url: "abc"};
}
<强>更新强>
在旁注中,您稍后仍可使用点表示法引用该值。 。 。例如,如果您想稍后检查“obj”是否具有“alpha”值,则可以使用if (obj.alpha . . .
或if {obj[alpha] . . .)
执行此操作,但只有括号表示方法才能使用一个动态的,基于变量的密钥(例如,if (obj[req.body.name] . . .)
)。
答案 2 :(得分:0)
如果我理解了你想要更新obj对象的问题吗?喜欢这样
obj['newKey'] = { status: true, url: "abc" }
答案 3 :(得分:0)
虽然我找不到合适的用例,但您始终可以将值存储在req.body.name
中并将其用作obj中的键,如下所示:
function abc(req, res, next) {
let imageName = req.body.name;
const obj = {}
obj[imageName] = {
status: true,
url: "abc"
}
}